Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
StringIndexOutOfBoundsException
Java Exceptions Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Exceptions Micro Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of understanding regarding Java exceptions.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
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.