Reputation: 1925
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!
Upvotes: 1
Views: 972
Reputation: 1499790
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
.
Upvotes: 7
Reputation: 2574
I think you are missunderstanding this by saying that"there is no 4 index as well but the outpul will be "n"" , the substring method counts from 1(not from 0) so your first example had nothing wrong with it because the fourth character was atually n.
Upvotes: 0
Reputation: 1586
substring(a,b) method of String object returns substring from index a to b-1 so substring(3,4) return only "N" i.e only index value 3. note that substring(a,a) returns always a null string.
Upvotes: 0
Reputation: 48807
From http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int):
Throws IndexOutOfBoundsException if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
You string's length is 4, so 4 is OK but 5 or more is KO.
Upvotes: 1