Reputation: 725
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?
Upvotes: 0
Views: 425
Reputation: 14051
The first argument of the method substring()
is the index of the beginning of your selection, and the second is the index of the end, not the length you want your selection to be as you apparently think.
See the documentation here.
Upvotes: 0