Home โบ Java exceptions โบ IndexOutOfBoundsException
IndexOutOfBoundsException: causes and fixes
A List or other indexed collection was accessed with an index outside its size.
What it looks like
java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3Extends RuntimeException in java.lang.
What it means
List implementations such as ArrayList throw IndexOutOfBoundsException from get, set, add(index, e) and remove(index) when the index is negative or not smaller than the size. It is the parent of ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException. An empty list is the most common trigger, because index 0 is already out of range.
Common causes
- Calling
list.get(0)on a list that is empty, for example a query that returned no rows. - Removing elements inside a loop that counts up, which shifts the remaining indexes.
- Using the size as an index, or an index computed from another collection with a different length.
- Calling
subList(from, to)with a range larger than the list.
How to fix it
- Check
isEmpty()orsize()before indexing. - Use streams or
findFirst()to get an Optional instead ofget(0). - Iterate with an Iterator and
remove(), or useremoveIf, when deleting while looping. - Use
List.getFirst()andgetLast()(Java 21) when you really want the ends; they throw a clearer NoSuchElementException.
Broken and fixed
List<Order> orders = repo.findByCustomer(id);
Order first = orders.get(0); // empty list -> exceptionOrder first = orders.stream().findFirst()
.orElseThrow(() -> new OrderNotFoundException(id));๐ Unravel the failing code ๐ Unravel the fix
In Spring and enterprise code
Repository and query methods return empty lists, not null, so get(0) without a size check is a very common production error in service code.
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 IndexOutOfBoundsException a checked or unchecked exception?
IndexOutOfBoundsException is an unchecked exception (it extends 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 IndexOutOfBoundsException in?
It lives in java.lang, so the import is import java.lang.IndexOutOfBoundsException; (java.lang needs no import).
What is the first thing to check when I see IndexOutOfBoundsException?
Read the message and the first stack trace line in your own code. The usual causes are: Calling list.get(0) on a list that is empty, for example a query that returned no rows; and Removing elements inside a loop that counts up, which shifts the remaining indexes.