BackendBench
Coffee

Home โ€บ Java exceptions โ€บ StringIndexOutOfBoundsException

Unchecked exception ยท java.lang

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 5

Extends 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

How to fix it

  1. Clamp the end: s.substring(0, Math.min(s.length(), 10)).
  2. Test the result of indexOf against -1 before using it.
  3. Validate the format with a regular expression or a parser before slicing.
  4. Use String.formatted, strip and split helpers or a library such as Apache Commons StringUtils.substring that tolerates short input.

Broken and fixed

fails
String code = id.substring(0, 4); // fails if id has fewer than 4 characters
works
String 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.

Related exceptions

More tools you might need