How to Fix java.lang.ArrayIndexOutOfBoundsException: Index X out of bounds for length Y

beginnerโ˜• Java2026-04-04| Java Runtime Environment (JRE) / Java Development Kit (JDK) - All Versions

Error Message

java.lang.ArrayIndexOutOfBoundsException: Index X out of bounds for length Y
#java#array#index#exception#ArrayIndexOutOfBoundsException

TL;DR: The Quick Fix

The java.lang.ArrayIndexOutOfBoundsException occurs when you try to access an array element at an index that doesn't exist. In Java, arrays are zero-indexed, meaning the valid range is from 0 to length - 1.

To fix this immediately, ensure your index satisfies this condition:

if (index >= 0 && index < array.length) {
    // Safe to access
    System.out.println(array[index]);
}

Commonly, this happens in loops where the exit condition is i <= array.length. Change it to i < array.length.

Understanding the Root Cause

Java arrays are fixed-size structures. When the JVM executes a line of code that requests an index outside the allocated memory range of that array, it throws this runtime exception to prevent memory corruption or unpredictable behavior.

The error message usually tells you exactly what went wrong:

java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5

In this example, the array has 5 slots (indices 0, 1, 2, 3, 4). Requesting index 5 is illegal because the highest available index is always length - 1.

Common Scenarios

- **The Off-by-One Loop:** Using `<=` instead of `<` in a for-loop header.
- **Empty Arrays:** Attempting to access `array[0]` on an array with a length of 0.
- **Hardcoded Indices:** Assuming an array will always have a certain size without checking first.
- **Negative Indices:** Accidentally calculating a negative number for an index (e.g., `i - 1` when `i` is 0).

Step-by-Step Fix Approaches

1. Correcting Loop Boundaries

This is the most frequent culprit. Junior developers often confuse the length of the array with the final index.

Broken Code:

int[] numbers = {10, 20, 30};
for (int i = 0; i <= numbers.length; i++) {
    System.out.println(numbers[i]); // Throws exception when i reaches 3
}

Fixed Code:

for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]); // Correct: loops through 0, 1, 2
}

2. Using the Enhanced For-Loop (For-Each)

If you don't need the actual index number for logic and only need the data inside, use the enhanced for-loop. This syntax makes it physically impossible to trigger an ArrayIndexOutOfBoundsException because the iteration logic is handled by the JVM.

String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
    System.out.println(name);
}

3. Defensive Bounds Checking

When dealing with dynamic input or data coming from a database/API, always validate the index before use. This is especially important for CLI arguments or user-submitted indices.

public void processElement(String[] data, int targetIndex) {
    if (data == null || data.length == 0) {
        System.err.println("Array is empty or null");
        return;
    }

    if (targetIndex < 0 || targetIndex >= data.length) {
        System.err.println("Invalid index: " + targetIndex);
        return;
    }

    System.out.println("Data: " + data[targetIndex]);
}

4. Debugging Index Calculations

If your index is the result of a calculation (like array[i + j - 1]), print the calculated value right before the crash point to see exactly what number is being generated.

int calculatedIndex = i + j - 1;
System.out.println("Debug: accessing index " + calculatedIndex + " for length " + array.length);
System.out.println(array[calculatedIndex]);

Verifying the Fix

To confirm your fix works, you should test the boundary conditions of your array:

- **Test with an empty array:** Does your code handle `length == 0` gracefully without crashing?
- **Test with a single-element array:** Ensure it reads `index 0` and stops.
- **Automated Unit Tests:** Use JUnit to verify that your methods return expected values or handle errors properly when passed out-of-bounds indices.
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testInvalidAccess() {
    int[] arr = {1, 2};
    int fail = arr[2]; // This should fail, allowing you to test your error handling logic
}

Further Reading

- [Official Oracle Docs: ArrayIndexOutOfBoundsException](https://docs.oracle.com/javase/8/docs/api/java/lang/ArrayIndexOutOfBoundsException.html)
- [Java Tutorials: Arrays](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)
- [Baeldung: Guide to ArrayIndexOutOfBoundsException](https://www.baeldung.com/java-array-index-out-of-bounds)

Related Error Notes