What is StringIndexOutOfBoundsException in Java?


Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String.

You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype).

String stringObject = new String("Hello how are you");
String stringLiteral = "Welcome to Tutorialspoint";

Since the string stores an array of characters, just like arrays the position of each character is represented by an index (starting from 0). For example, if we have created a String as −

String str = "Hello";

The characters in it are positioned as −

If you try to access the character of a String at the index which is greater than its length a StringIndexOutOfBoundsException is thrown.

Example

The String class in Java provides various methods to manipulate Strings. You can find the character at a particular index using the charAt() method of this class.

This method accepts an integer value specifying the index of the String and returns the character in the String at the specified index.

In the following Java program, we are creating a String of length 17 and trying to print the element at index 40.

 Live Demo

public class Test {
   public static void main(String[] args) {
      String str = "Hello how are you";
      System.out.println("Length of the String: "+str.length());
      for(int i=0; i<str.length(); i++) {
         System.out.println(str.charAt(i));
      }
      //Accessing element at greater than the length of the String
      System.out.println(str.charAt(40));
   }
}

Output

Run time exception −

Since we are accessing the element at the index greater than its length StringIndexOutOfBoundsException is thrown.

Length of the String: 17
H
e
l
l
o
h
o
w
a
r
e
y
o
u
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 40
   at java.base/java.lang.StringLatin1.charAt(Unknown Source)
   at java.base/java.lang.String.charAt(Unknown Source)
   at Test.main(Test.java:9)
raja
Published on 15-Oct-2019 10:40:53
Advertisements