Add to Google Reader or Homepage

Exception in thread "main" java.lang.StringIndexOutOfBoundsException

StringIndexOutOfBounds Exception:


The StringIndexOutOfBoundsException is one of the common exception that is experienced by most of the java programmers when dealing with strings in the java program.Let us have a quick overview of why this exception is thrown and how to deal with the same.

What is meant by StringOutOf BoundsException?

As the name itself indicates that the index we are trying to access or modify in the string is out of its bounds(length).This exception belongs to the java.lang.package.

In Java API it was given as follows:

A StringIndexOutOfBoundsException is thrown by string methods to indicate that the specified index is either negative or greater than the size of the string.For Methods such as the charAt() method this exception is also thrown when the index is also equal to the size of the String.

When this exception is thrown?

When we try to access a particular index of the string which is either greater or  negative than the size of the string then this exception will be thrown.

How to fix this exception?

As we know the cause of this exception the solution is more obvious that we have to change the index value to be within the bounds.

Example situations for this exception:

import java.io.*;
import java.lang.*;
import java.util.*;
public class Illegalarg1
{
public static void main(String args[])
{
String test="HELLO";
char in;
String index=null;
System.out.println("Enter the index:");
Scanner br =new Scanner(new InputStreamReader(System.in));
index = br.nextLine();
try {
      in= test.charAt(Integer.parseInt(index));
      System.out.println("The char at the specified index is:"+in);
   }
   catch ( IllegalArgumentException e ) {
      System.out.println("Illegal Argument Exception");
      System.out.println("Type the integer value for the index" );
   }
}
}

Error:

Enter the index:
9
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range: 9
        at java.lang.String.charAt(Unknown Source)
        at Illegalarg1.main(Illegalarg1.java:16)

In the above program i have tried to access the character at index 9 which is greater than the size of the string which causes this exception to be thrown. 



0 comments:

Post a Comment

 
java errors and exceptions © 2010 | Designed by Chica Blogger | Back to top