masato-san masato-san - 7 months ago 22
Java Question

substring(startIndex, endIndex) - why is "out of range" not thrown?

In Java I am using the

substring()
method and I'm not sure why it is not throwing an "out of index" error.

The string
abcde
has index start from 0 to 4 but
substring()
method takes startIndex and endIndex as arguments based on the fact that I can call foo.substring(0) and get "abcde"

Then why does substring(5) work? That index should be out of range. Could anyone explain to me?

/*
1234
abcde
*/
String foo = "abcde";
System.out.println(foo.substring(0));
System.out.println(foo.substring(1));
System.out.println(foo.substring(2));
System.out.println(foo.substring(3));
System.out.println(foo.substring(4));
System.out.println(foo.substring(5));


This code outputs:

abcde
bcde
cde
de
e
//foo.substring(5) output nothing here, isn't this out of range?


When I replace 5 with 6:

foo.substring(6)


Then I get error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1

Answer

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.