• Register
3,890 points
11 5 1
Welcome to Kodlogs, programming questions and answer website.

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

The String can be created by using either by using a new keyword or assigning the value to literal. Since the strings are used to store an array of characters so the position of each character is represented by using an index.

Reason of error:

When the user tries to access the character of a String at an index that is greater than its index then StringIndexOutOfBoundsException is thrown.

Example code:

In this code, we are going to create a String of length 17 and try to print out elements at index 40.

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:

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.lang.String.charAt(String.java:658)

      at Test.main(Test.java:9)

 

3,890 points
11 5 1