Home โบ Java exceptions โบ ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException: causes and fixes
An array was accessed with an index below zero or at or beyond its length.
What it looks like
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5Extends IndexOutOfBoundsException in java.lang.
What it means
Java arrays have a fixed length and valid indexes run from 0 to length minus 1. Reading or writing any other index throws this exception, with a message that gives both the index and the length. It is almost always an off-by-one in a loop or an assumption about the size of data that arrived from outside the program.
Common causes
- A loop condition of
i <= array.lengthinstead ofi < array.length. - Using the last index plus one, or a negative index from arithmetic such as
i - 1at i = 0. - Splitting a string and assuming a number of parts:
line.split(",")[2]on a short line. - Reading command-line arguments or a CSV row without checking its length.
How to fix it
- Compare the index with
array.lengthbefore using it, or iterate with an enhanced for loop. - Check the result of
splitbefore indexing, and use the limit argument when the trailing parts matter. - Use a List and its methods when the size changes, instead of resizing arrays by hand.
- Log the index and length (the message already contains them) to see which assumption failed.
Broken and fixed
for (int i = 0; i <= values.length; i++) {
sum += values[i]; // fails when i == values.length
}for (int i = 0; i < values.length; i++) {
sum += values[i];
}๐ Unravel the failing code ๐ Unravel the fix
In Spring and enterprise code
Input parsing code is the usual source in services: a file with a missing column or a message with fewer fields than expected. Validate the shape of external data before indexing into it.
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 ArrayIndexOutOfBoundsException a checked or unchecked exception?
ArrayIndexOutOfBoundsException 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 ArrayIndexOutOfBoundsException in?
It lives in java.lang, so the import is import java.lang.ArrayIndexOutOfBoundsException; (java.lang needs no import).
What is the first thing to check when I see ArrayIndexOutOfBoundsException?
Read the message and the first stack trace line in your own code. The usual causes are: A loop condition of i <= array.length instead of i < array.length; and Using the last index plus one, or a negative index from arithmetic such as i - 1 at i = 0.