Why does the following Java code snippet throw a StringIndexOutOfBoundsException on the third line of code?
String str = "1234567890";
String sub1 = str.substring(0, 3);
String sub2 = str.substring(4, 1);
I’d have expected the result of the above code to be that sub1 contains “123” and sub2 contains “5”, but instead I get the exception mentioned above. Does the first substring call have have side-effect on the string being operated on?
Because
beginIndexis larger thanendIndexSee the doc:
Throws:
IndexOutOfBoundsException – if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.