StringIndexOutOfBoundsException

Examples of Exceptions

StringIndexOutOfBoundsException

🙋 Need help? Ask an expert now!

The "StringIndexOutOfBoundsException" is similar to the "ArrayIndexOutOfBoundsException" we already covered. When the index of the targeted value is less than zero or greater than or equal to the length of the String, the exception occurs. Take a look at the example below.

StringIndexOutOfBoundsExample.java
package exlcode;

public class StringIndexOutOfBoundsExample {

  public static String exampleVariableOne = "Hello World!";

  public static void main(String[] args) {
    try {
      // StringIndexOutOfBoundsException will be thrown because
      // exampleVariableOne only has a length of 12
      exampleVariableOne.charAt(13);
      System.out.println("String Index is valid");
    } catch (StringIndexOutOfBoundsException e) {
      System.out.println("String Index is out of bounds");
    }
  }
}

The exception occurs when the index of a value does not exist in the String we call. The code we examined above attempts to access the character at the thirteenth index of exampleVariableOne, which only has a length of twelve and a maximum index of eleven. Play around with the index number to stop the exception from occurring.

A great way to avoid this exception is to use something like stringname.length()-1 for the last index instead of putting a specific value, which may turn out to be incorrect and cause the error. Keep in mind that the length of a String can change if concatenation is used. Only use specific index values if you are completely certain about the number of characters inside the String.

Edit Me on GitHub!

Application Question

Which of the following throws a StringIndexOutOfBoundsException?