1. Introduction
When you manipulate the characters of a String
object in Java, a StringIndexOutOfBoundsException may be thrown if you’re not careful enough. This article will guide you through resolving this exception and provide best practices to prevent it.
2. What Java Says about StringIndexOutOfBoundsException
According to the Javadoc, a StringIndexOutOfBoundsException is 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.
3. How to Reproduce StringIndexOutOfBoundsException
Let’s consider the following code snippet which creates a simple String literal:
String name = "John Doe";//String length is 8
If you attempt to call the charAt()
with an index out of the range [0, 7], a StringIndexOutOfBoundsException will be thrown:
String name = "John Doe";//String length is 8
char c = name.charAt(10);
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:1512)
at Scratch.main(scratch.java:6)
Just like arrays, strings are zero-based, meaning that the first character is at index 0 and the last character is at index String#length() - 1
.
The solution here is to ensure that the index you provide falls in the valid range [0, yourString.length – 1]
String name = "John Doe";//String length is 8
char c = name.charAt(3);// n
4. Best Practices to Avoid StringIndexOutOfBoundsException
4.1. Check bounds before accessing elements
Before calling any method on the String class which manipulates characters based on an index, you should check for boundaries:
String name = "John Doe";//String length is 8
int index = 10;
if(index >=0 && index < name.length()){//boundaries check
char c = name.charAt(index);//No StringIndexOutOfBoundsException since the code does not pass here
}
4.2. Use loops safely
Another best practice is to pay attention to indices while looping on characters of a String object.
String name = "John Doe";//String length is 8
for(int i = 0; i < name.length(); i++){//OK. Use the correct boundaries: i >=0 and i < name.length()
char c = name.charAt(i);
//Your code here
}
Always give special attention to edge cases as they often lead to StringIndexOutOfBoundsException
4.3. Prefer enhanced for-loop
To avoid dealing with indices, use the enhanced for-loop whenever possible.
String name = "John Doe";//String length is 8
for(char c : name.toCharArray()){//Enhanced for-loop
//Your code here
}
5. Conclusion
In this brief tutorial, you learned about the StringIndexOutOfBoundsException and how to fix it.
You can find the complete code of this article here in GitHub