Home > Java > javaTutorial > body text

What does StringIndexOutOfBoundsException mean in Java?

WBOY
Release: 2023-09-05 13:29:06
forward
897 people have browsed it

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";
Copy after login

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";
Copy after login

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));
   }
}
Copy after login

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)
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template