Home  >  Article  >  Java  >  What does StringIndexOutOfBoundsException mean in Java?

What does StringIndexOutOfBoundsException mean in Java?

WBOY
WBOYforward
2023-09-05 13:29:06901browse

In Java, strings are used to store sequences of characters, and they are treated as objects. The String class in the java.lang package represents a string.

You can create a string by using the new keyword (like any other object) or by assigning a value to a literal (like any other primitive data type).

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

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

String str = "Hello";

where the characters are positioned as −

What does StringIndexOutOfBoundsException mean in Java?

If you try to access the string with an index greater than its characters of length, a StringIndexOutOfBoundsException exception will be thrown.

Example

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

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

In the following Java program, we create a string of length 17 and try to print the element with index 40.

Demonstration

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

Runtime exception-

Because we access an element at an index greater than its length, it will Throws StringIndexOutOfBoundsException.

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)

The above is the detailed content of What does StringIndexOutOfBoundsException mean in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete