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 the 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. What is the explanation?
/*
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
According to the Java API doc, substring throws an error when the start index is greater than the Length of the String.
In fact, they give an example much like yours:
I guess this means it is best to think of a Java String as the following, where an index is wrapped in
|:Which is to say a string has both a start and end index.