Cleggy
Cleggy

Reputation: 725

Why do I get a StringIndexOutOfBoundsException on the second line here?

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

Answers (3)

talnicolas
talnicolas

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

KV Prajapati
KV Prajapati

Reputation: 94653

Take a look at doc : String.substring(beginIndex,endIndex)

Upvotes: 1

OscarRyz
OscarRyz

Reputation: 199333

Because beginIndex is larger than endIndex

See 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.

Upvotes: 5

Related Questions