Why is “out of range” not thrown for ‘substring(startIndex, endIndex)’

According to the Java API doc, substring throws an error when the start index is greater than the Length of the String.

IndexOutOfBoundsException – if
beginIndex is negative or larger than
the length of this String object.

In fact, they give an example much like yours:

"emptiness".substring(9) returns "" (an empty string)

I guess this means it is best to think of a Java String as the following, where an index is wrapped in |:

|0| A |1| B |2| C |3| D |4| E |5|

Which is to say a string has both a start and end index.

Leave a Comment