Reputation: 347
Suppose I have a
String temp = "abcd";
System.out.println(temp.substring(0,4)); // out of bound, no error
System.out.println(temp.substring(0,5)); // out of bound, error
Why?
Upvotes: 0
Views: 273
Reputation: 304
The substring(0,4) does not consider 0 to 4. It considers 0 to 3. The 2nd index is always subtracted by 1. In your second case temp[4] is out of bounds.
Upvotes: 0
Reputation: 5831
According to docs:
public String substring(int beginIndex, int endIndex)
The substring begins at the specified
beginIndex
and extends to the character at indexendIndex - 1
.
IndexOutOfBoundsException
- if thebeginIndex
is negative, orendIndex
is larger than the length of this String object, orbeginIndex
is larger thanendIndex
.
Since System.out.println(temp.substring(0,5));
where 5 > length of string (abcd
), hence the exception.
Upvotes: 1
Reputation: 178243
The Javadocs for this method state:
The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Throws:
IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
An end index of length
is ok, but length + 1
is not.
Upvotes: 3