Sunday, December 12, 2010

Substring Index Out of Range or StringIndexOutOfBoundsException Java

While working with Strings in Java, we may get StringIndexOutOfBoundsException for the substring() method of the String class. This is to signify that the Index specified is out of the range.

For substring() method, we need to provide the start and end index values or only the start index value. The index value of String in Java starts from 0 and goes till one less then the string length. Substring method uses this information to extract a part of the original String.

While extracting a part of the String, if the starting index value is negative, or the end index value is greater then the String length. If such a case occurs then we get an StringIndexOutOfBoundsException, it is a message from the JVM to tell us that the index is out of range.

The below examples clarify it better:-

Reasons for StringIndexOutOfBoundsException 

The below code explains the occurrence of the StringIndexOutOfBoundsException.

     package JavaTest1;

    public class IndexOutOfRangeExample {

        /**
         * @param args
         */
        public static void main(String[] args) {

            String str = "Testing a string for Index out of range";
            System.out.println("The original String is: " + str);
            System.out.println("The length of the String is: " + str.length());

            str = str.substring(-1);

            System.out.println("The modified String is: " + str);
        }
    }

The above code will result in a run time exception. The output is shown below:-
    The original String is: Testing a string for Index out of range
    The length of the String is: 39
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
        at java.lang.String.substring(Unknown Source)
        at java.lang.String.substring(Unknown Source)
        at JavaTest1.IndexOutOfRangeExample.main(IndexOutOfRangeExample.java:14)


 The line str = str.substring(-1); is the root cause of this error. We will get the same exception if the line is replaced with any of the below line examples:-
  •  str = str.substring(0, 40);   //The length of the string considered is 39, so anything greater will cause index out of range.
  • str = str.substring(40, 49);   //The start index value is larger then the length of the String, so again the exception will be thrown.
  • str = str.substring(40);
  • str = str.substring(-58); //  Negative value for start index is cause of exception.
 To avoid this exception, make sure that you stay within the bounds of the String length.

Related Articles

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.