what does "java.lang.stringindexoutofboundsexception string index out of range: -2" mean? I know the -1 thing but what does -2 imply?
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
what does "java.lang.stringindexoutofboundsexception string index out of range: -2" mean? I know the -1 thing but what does -2 imply?
The -2 is the value of the index that was out of bounds.
If you don't understand my answer, don't ignore it, ask a question.
Hello,
I would like to provide an example that will clarify this exception but before that we need to look at the substring(int beginIndex, int endIndex) method. The two method parameters int beginIndex and int endIndex have a key difference:
beginIndex is 0 based
endIndex is 1 based
And here is an example to illustrate this:
public static void main(String[] args) { String str = "012345"; System.out.println(str.substring(0, 1); }
This will print "0" and here is why
0 based indexes of our string:
String str = "012345";
INDEXES 012345
1 based indexes of our string:
String str = "012345";
INDEXES 123456
you can play with the indexes and you can even say str.substring(3, 3) which will print an empty string "".
Now to go back to our exception java.lang.StringIndexOutOfBoundsException -2
This exception will be thrown when the endIndex is beginIndex = endIndex - 2 which in our case is str.substring(3, 1)
The following code will throw java.lang.StringIndexOutOfBoundsException -2:
public static void main(String[] args) { String str = "012345"; System.out.println(str.substring(3, 1); }
I hope this helps.
Regards
Alin
Last edited by Alin; August 2nd, 2018 at 05:43 AM.