StringIndexOutOfBoundsException

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.

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

Looking to contribute?

Learn Java on Codecademy