In this Java tutorial, you will learn when java.lang.StringIndexOutOfBoundsException occurs, why the message says String index out of range, and how to fix it by validating string indexes before calling methods such as charAt(), substring(), and subSequence().
What does java.lang.StringIndexOutOfBoundsException mean?
StringIndexOutOfBoundsException is thrown when Java code tries to use an invalid index with a String. A string index is zero-based, which means the first character is at index 0, and the last character is at index str.length() - 1.
For example, if a string has a length of 22, valid character indexes are from 0 to 21. Using 22, 36, or a negative index such as -1 as a character index is outside the allowed range.
How does StringIndexOutOfBoundsException occur ?
String is kind of an ensemble of characters. String object has a range of [0,length of the string]. When someone tries to access the characters with limits exceeding the range of actual string value, java.lang.StringIndexOutOfBoundsException: String index out of range occurs.
In practice, this exception commonly appears in the following situations.
- Calling
str.charAt(index)withindex < 0orindex >= str.length(). - Calling
str.substring(beginIndex, endIndex)wherebeginIndexis negative,endIndexis greater than the string length, orbeginIndex > endIndex. - Assuming a string always has a fixed length when the input may be shorter, empty, or generated dynamically.
- Using loop conditions such as
i <= str.length()instead ofi < str.length().
Example
In the following program, we shall try to access the characters out of range, using String.substring() method.
Example.java
public class Example {
public static void main(String[] args) {
String str = "Learning Java is easy.";
String strPart = str.substring(14,36);
System.out.println("strPart : " +strPart);
}
}
When the program is run, str.substring(14,36) tries to access characters from index 14 to 36 in the string str. Since the length of the string is only 21, java runtime does not allow us to access any character beyond the limit of 21, which in this case thows java.lang.StringIndexOutOfBoundsException: String index out of range: 36 as shown below.
strPart1 : Learning Java
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 36
at java.lang.String.substring(Unknown Source)
at com.tut.StringIndexOutOfBoundsExceptionExample.main(StringIndexOutOfBoundsExceptionExample.java:12)
To debug this type of error, first check the value mentioned in the exception message. In this example, 36 is the invalid index. Then compare that value with str.length(). If the index is outside the valid range, adjust the index calculation or add a boundary check before accessing the string.
String index rules for charAt() and substring()
The valid range depends on the string method you are calling. charAt() needs a real character position, but substring() uses a start index and an end index. The end index in substring(beginIndex, endIndex) is exclusive, so the character at endIndex is not included in the result.
| Java String operation | Valid index rule | Invalid example |
|---|---|---|
str.charAt(index) | 0 <= index < str.length() | str.charAt(str.length()) |
str.substring(beginIndex) | 0 <= beginIndex <= str.length() | str.substring(str.length() + 1) |
str.substring(beginIndex, endIndex) | 0 <= beginIndex <= endIndex <= str.length() | str.substring(14, 36) when length is 22 |
Notice that substring() allows endIndex == str.length(), because the end index is exclusive. But charAt(str.length()) is invalid, because there is no character at that position.
How to handle java.lang.StringIndexOutOfBoundsException: String index out of range ?
1. Manually check the string length
To handle this exception by yourself, check the string length before operations like substring.
public class Example {
public static void main(String[] args) {
String str = "Learning Java is easy.";
System.out.println("Length of str is : "+str.length());
if(13<str.length()){
String strPart1 = str.substring(0,13);
System.out.println("strPart1 : " +strPart1);
}
if(36<=str.length()){
String strPart2 = str.substring(14,36);
System.out.println("strPart2 : " +strPart2);
}
System.out.println("Action of accessing chars is taken after checking range of string, str. StringIndexOutOfBoundsException is handled.");
}
}
When the program is run, as the str.length = 22 and 36 is not less than or equal to 22, we avoided executing the line that shall cause StringIndexOutOfBoundsException.
Output
Length of str is : 22
strPart1 : Learning Java
Action of accessing chars is taken after checking range of string, str. StringIndexOutOfBoundsException is handled.
A clearer version is to calculate the string length once and check both substring boundaries before calling substring().
public class Example {
public static void main(String[] args) {
String str = "Learning Java is easy.";
int beginIndex = 14;
int endIndex = 36;
if (beginIndex >= 0 && endIndex <= str.length() && beginIndex <= endIndex) {
String strPart = str.substring(beginIndex, endIndex);
System.out.println(strPart);
} else {
System.out.println("Invalid substring range for the given string.");
}
}
}
Output
Invalid substring range for the given string.
2. Use try-catch
You can also use try-catch block around the code snippet, that could possibly throw StringIndexOutOfBoundsException, as shown in the following program.
public class Example {
public static void main(String[] args) {
String str = "Learning Java is easy.";
try {
String substr = str.substring(20,36);
System.out.println("Sub string : " +substr);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Exception caught in catch block.");
}
}
}
When the program is run, str.substring(14,36) causes StringIndexOutOfBoundsException, where in the catch block has cought the exception and proceed with the rest of execution. The output is shown below:
Exception caught in catch block.
Use try-catch when invalid input is possible and you want the program to continue safely. For normal string processing, checking the index range before the string operation is usually easier to read and avoids using exceptions as regular control flow.
Fix StringIndexOutOfBoundsException in charAt() loops
A frequent cause of StringIndexOutOfBoundsException is an off-by-one error in a loop. Since the last valid index is str.length() - 1, the loop condition should be i < str.length(), not i <= str.length().
public class Example {
public static void main(String[] args) {
String str = "Java";
for (int i = 0; i < str.length(); i++) {
System.out.println(str.charAt(i));
}
}
}
Output
J
a
v
a
If the condition is changed to i <= str.length(), the loop tries to read str.charAt(4) for the string "Java". That fails because the valid indexes are only 0, 1, 2, and 3.
Safe substring helper for dynamic input strings
When indexes come from user input, file data, API response data, or another calculation, validate the range in one place. The following helper method returns an empty string when the requested range is invalid.
public class Example {
static String safeSubstring(String str, int beginIndex, int endIndex) {
if (str == null) {
return "";
}
if (beginIndex < 0 || endIndex > str.length() || beginIndex > endIndex) {
return "";
}
return str.substring(beginIndex, endIndex);
}
public static void main(String[] args) {
String text = "Learning Java is easy.";
System.out.println(safeSubstring(text, 0, 13));
System.out.println(safeSubstring(text, 14, 36));
}
}
Output
Learning Java
The second call prints an empty line because 36 is greater than the string length. In a real application, you may return a default value, log the invalid input, or show a validation message depending on the use case.
StringIndexOutOfBoundsException vs IndexOutOfBoundsException in Java
StringIndexOutOfBoundsException is specific to string operations. IndexOutOfBoundsException is a more general exception for invalid indexes in indexed data structures and operations. For example, list operations may throw IndexOutOfBoundsException, while string operations such as charAt() and substring() may throw StringIndexOutOfBoundsException.
The fix is similar in both cases: check the valid index range before accessing the value, and do not assume that input always has the expected length.
Checklist to avoid String index out of range errors
- Check
str.length()before using a hard-coded string index. - Use
i < str.length()in loops that callcharAt(i). - For
substring(beginIndex, endIndex), confirm thatbeginIndexis not negative,endIndexis not greater than the string length, andbeginIndexis not greater thanendIndex. - Handle empty strings before reading the first or last character.
- Validate external input before extracting fixed-position values such as codes, dates, or prefixes.
Java Reference
Java doc to java.lang StringIndexOutOfBoundsException is available at https://docs.oracle.com/javase/8/docs/api/java/lang/StringIndexOutOfBoundsException.html
FAQs on java.lang.StringIndexOutOfBoundsException
How do I fix StringIndexOutOfBoundsException in Java?
Find the invalid index from the exception message or stack trace, compare it with str.length(), and update the code so the index stays within the valid range. For charAt(), the index must be from 0 to str.length() - 1. For substring(), the end index can be equal to str.length() because it is exclusive.
Why does charAt(str.length()) throw String index out of range?
charAt(str.length()) throws the exception because string indexes start at 0. If the length is 4, the valid character indexes are 0, 1, 2, and 3. There is no character at index 4.
Can substring() use an end index equal to the string length?
Yes. In substring(beginIndex, endIndex), the endIndex is exclusive, so endIndex == str.length() is valid. But endIndex > str.length() is invalid and may throw StringIndexOutOfBoundsException.
Should I use try-catch or length checks for StringIndexOutOfBoundsException?
Use length checks when the index can be validated before the string operation. Use try-catch when you are handling unexpected invalid input and need the program to continue safely. For most normal string parsing code, explicit boundary checks are clearer.
Conclusion
In this tutorial, we have presented what java.lang StringIndexOutOfBoundsException: String index out of range exception is, and how to handle this exception in two different ways.
The main fix is to validate string indexes before accessing the string. Check the string length, use correct loop boundaries, remember that substring() has an exclusive end index, and use try-catch only where exception handling is the right flow for your program.
TutorialKart.com