Java StringIndexOutOfBoundsException

Christine_Yang's avatar
Published Aug 22, 2022Updated Aug 22, 2022
Contribute to Docs

The StringIndexOutOfBoundsException is an exception that occurs when a String method tries to use an index that is either negative or greater than the size of the String.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Example

The following example creates a StringIndexOutOfBoundsException:

public class ErrorExample {
public static void main(String[] args) {
String greeting = "Hello World";
System.out.println(greeting.charAt(-1));
}
}

The output is something like this:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:1512)
at ErrorExample.main(ErrorExample.java:4)

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours