I came across some substring() method mystery and not sure why it is not throwing out of index error. The string "abcde" has index start from 0 to 4 but substring() method takes startIndex and endIndex as arguments which I believe zero base based on the fact that I can call foo.substring(0) and get "abcde"
Then why substring(5) works??? That index should be out of range. Could anyone explain to me?
/*
* 01234
* 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));
System.out.println("-----------------");
This code outputs:
abcde
bcde
cde
de
e
//foo.substring(5) output nothing here, isn't this out of range?
-----------------
The last one foo.substring(5) is pointing of non existing index but it does not throw an error. But 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