Java Reference
In-Depth Information
Common Programming Error
String Index Out of Bounds
It's very easy to forget that the last index of a String of length n is actually n - 1.
Forgetting this fact can cause you to write incorrect text-processing loops like
this one:
// This version of the code has a mistake!
// The test should be i < s.length()
public static int indexOf(char ch, String s) {
for (int i = 0; i <= s.length(); i++) {
if (s.charAt(i) == ch) {
return i;
}
}
return -1;
}
The program will throw an exception if the loop runs past the end of the
String . On the last pass through the loop, the value of the variable i will be
equal to s.length() . When it executes the if statement test, the program will
throw the exception. The error message will resemble the following:
Exception in thread "main"
java.lang.StringIndexOutOfBoundsException:
String index out of range: 11
at java.lang.String.charAt(Unknown Source)
at OutOfBoundsExample.indexOf(OutOfBoundsExample.java:9)
at OutOfBoundsExample.main(OutOfBoundsExample.java:4)
An interesting thing about the bug in this example is that it only occurs if the
String does not contain the character ch . If ch is contained in the String , the
if test will be true for one of the legal indexes in s , so the code will return that
index. Only if all the characters from s have been examined without finding ch
will the loop attempt its last fatal pass.
It may seem strange that we don't have a test for the final return statement
that returns -1 , but remember that the for loop tries every possible index of the
String searching for the character. If the character appears anywhere in the
String , the return statement inside the loop will be executed and we'll never get
to the return statement after the loop. The only way to get to the return state-
ment after the loop is to find that the character appears nowhere in the given
String .
 
Search WWH ::




Custom Search