StringIndexOutOfBoundsException in Java with Example

This Java example demonstrates the usage of java.lang.StringIndexOutOfBoundsException class and when does this exception occur with an example.
This StringIndexOutOfBoundsException object thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string.

StringIndexOutOfBoundsException Class Diagram

Java StringIndexOutOfBoundsException Example

In this below example, the exception occurred because the referenced index was not present in the String.
package com.javaguides.corejava;

public class StringIndexOutOfBounds {

    public static void main(String[] args) {

        String str = "Hello World";
        try {
            char charAtNegativeIndex = str.charAt(-1); // Trying to access at negative index
            char charAtLengthIndex = str.charAt(11); // Trying to access at index equal to size of the string
        } catch (StringIndexOutOfBoundsException e) {
            System.err.println("StringIndexOutOfBoundsException caught");
            e.printStackTrace();
        }
    }
}
Output:
StringIndexOutOfBoundsException caught
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
 at java.lang.String.charAt(String.java:658)
 at com.javaguides.corejava.StringIndexOutOfBounds.main(StringIndexOutOfBounds.java:9)

Reference

Comments