Home โบ Java exceptions โบ StringIndexOutOfBoundsException
StringIndexOutOfBoundsException: causes and fixes
A String method such as charAt or substring was given an index outside the string.
What it looks like
java.lang.StringIndexOutOfBoundsException: Range [3, 10) out of bounds for length 5Extends IndexOutOfBoundsException in java.lang.
What it means
Strings are indexed like arrays, from 0 to length minus 1. charAt, substring, codePointAt and similar methods throw this exception when an index or range is invalid. For substring(begin, end) the end is exclusive and the range must satisfy 0 <= begin <= end <= length, so both parts of the check matter. The message depends on the JDK: Java 21 prints "Range [3, 10) out of bounds for length 5", Java 17 and older print "begin 3, end 10, length 5".
Common causes
- Calling
substring(0, 10)on a string that may be shorter than ten characters. - Using
indexOfwithout checking for -1 and then passing the result tosubstring. - Assuming a fixed format (a date, an id with a prefix) for input that does not always follow it.
- Mixing up the start and end arguments, or treating the second argument of
substringas a length.
How to fix it
- Clamp the end:
s.substring(0, Math.min(s.length(), 10)). - Test the result of
indexOfagainst -1 before using it. - Validate the format with a regular expression or a parser before slicing.
- Use
String.formatted,stripand split helpers or a library such as Apache CommonsStringUtils.substringthat tolerates short input.
Broken and fixed
String code = id.substring(0, 4); // fails if id has fewer than 4 charactersString code = id.length() >= 4 ? id.substring(0, 4) : id;๐ Unravel the failing code ๐ Unravel the fix
Debug it faster
Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.
Frequently asked questions
Is StringIndexOutOfBoundsException a checked or unchecked exception?
StringIndexOutOfBoundsException is an unchecked exception (it extends IndexOutOfBoundsException, which is a RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.
Which package is StringIndexOutOfBoundsException in?
It lives in java.lang, so the import is import java.lang.StringIndexOutOfBoundsException; (java.lang needs no import).
What is the first thing to check when I see StringIndexOutOfBoundsException?
Read the message and the first stack trace line in your own code. The usual causes are: Calling substring(0, 10) on a string that may be shorter than ten characters; and Using indexOf without checking for -1 and then passing the result to substring.