A StringIndexOutOfBounds exception is an exception thrown by String methods to indicate that the index of its character is out of bounds: i.e. either negative, or greater (sometimes equal to) the length of the string. Use this tag when you are indexing Strings and you unexpectedly face a StringIndexOutOfBounds.
A StringIndexOutOfBounds
is a runtime exception in Java when you use a String method involving indexing one of its characters, but the index is out of bounds: negative or greater (sometimes equal to) the length of the String. Note that the indices of the characters of a String starts at zero, much like the indices of arrays.
If you index a String out of bounds, Java will throw a StringIndexOutOfBoundsException
. It extends IndexOutOfBoundsException
which may happen when indexing an array out of bounds.
Here is an example case of a StringIndexOutOfBoundsException
:
public static void main(String[] args) {
String s = "ABC"; // s.length() is 3.
System.out.println(s.charAt(3)); // Indexes run from 0 to 2.
}
When running this method, Java will throw an exception. Here is an example stack trace:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(Unknown Source)
at m2APR.StringIndexOutOfBounds.main(StringIndexOutOfBounds.java:6)
The Oracle documentation can be found here: https://docs.oracle.com/javase/7/docs/api/java/lang/StringIndexOutOfBoundsException.html