.

StringIndexOutOfBoundsException: String index out of range: -1

 
If you see StringIndexOutOfBoundsException in your java program then this is right post for you. This exception is thrown by the methods of String class which means that the index you are tying to access is either negative, or greater than size of the string . In some cases this exception is thrown even if index is equal to size of the string.

The java.lang.StringIndexOutOfBoundsException class extends the IndexOutOfBoundsException class, which is used to indicate that an index to either an array, a string, or a vector, is out of range.
 


Example:

public static void main(String[] args) {
       
        StringBuilder s = new StringBuilder();
        s.append("How are you?");
       
        for (int i=0; i<=100; i++){
            System.out.println(s.toString().substring(i,i+1));
        }
    }


Output:
H
o
w

a
r
e

y
o
u
?
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 13
    at java.lang.String.substring(Unknown Source)
    at stepTraining.StringOutOfBoundException.main(StringOutOfBoundException.java:11)



 


Solution:
 
This error comes when you try to access the index which does not exist. In above example, the length of string is 13 and the code is trying to access 13th element whose index is 12.

No comments :

Post a Comment

Recent Posts