BackendBench
Coffee

Home โ€บ Java exceptions โ€บ ArrayIndexOutOfBoundsException

Unchecked exception ยท java.lang

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 5

Extends 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

How to fix it

  1. Compare the index with array.length before using it, or iterate with an enhanced for loop.
  2. Check the result of split before indexing, and use the limit argument when the trailing parts matter.
  3. Use a List and its methods when the size changes, instead of resizing arrays by hand.
  4. Log the index and length (the message already contains them) to see which assumption failed.

Broken and fixed

fails
for (int i = 0; i <= values.length; i++) {
    sum += values[i]; // fails when i == values.length
}
works
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.

Related exceptions

More tools you might need