It seems like a simple question but I'm wondering why if I had some String variable like this:
String name = "John";
And then I'm using the substring method like this :
System.out.print(name.substring(3,4));
it works fine but if i'd change 4 for 5 or higher I get IndexOutOfBoundsException
. But as i understand indexes correct there is no 4 index as well but the outpul will be "n"
J O H N
0 1 2 3
Could someone explain such behavior? Thanks in advance!
The second parameter to substring
is an exclusive upper bound - so it's allowed to be equal to the length of the string, in order to include the last character. Likewise it makes sense to allow the starting point to be "at" the end of the string, so long as the end is equal to the start, yielding an empty string.
Basically, for APIs which deal with ranges, it often makes sense to think of the indexes as being "between" characters rather than "on" them. For example:
J O H N
^ ^ ^ ^ ^
0 1 2 3 4
Both indexes have to be within the range shown, and the endIndex
index must be either the same as beginIndex
or to the right - then the substring is the characters between the two corresponding boundaries:
"JOHN".substring(1, 3) is "OH"
J O H N
^ ^ ^
1 3
This is exactly as documented, of course
IndexOutOfBoundsException
- if thebeginIndex
is negative, orendIndex
is larger than the length of this String object, orbeginIndex
is larger thanendIndex
.
See more on this question at Stackoverflow