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