Tutorials Logic, IN info@tutorialslogic.com

ArrayIndexOutOfBoundsException in Java Fix: Causes and Fixes

Detailed Boundary Notes

An array of length n accepts indexes 0 through n - 1; index n, negative indexes, and stale indexes after data changes are invalid.

To fully understand this exception, always connect the error message to the array length and the index used. Valid indexes start at 0 and end at length - 1, so an array of length 5 accepts indexes 0, 1, 2, 3, and 4 only.

This exception is also common when reading user input, splitting strings, or processing command-line arguments. Always check the size of the array that was produced, not the size you expected from the input.

For nested loops and two-dimensional arrays, check row length and column length separately. Using the outer array length for every inner row can fail when rows have different sizes.

Log the attempted index and current length, then repair the boundary calculation rather than hiding the exception with a broad catch.

ArrayIndexOutOfBoundsException is a boundary error. It happens when code asks for an index that is negative or greater than the last valid index. The most common cause is using <= instead of < in a loop condition.

When you debug it, print or inspect three values together: the array length, the current index, and the loop condition. If those three values are clear, the fix is usually obvious.

  • For an array with length n, the last valid index is n - 1.
  • Use i < array.length in forward loops.
  • Use i >= 0 in reverse loops.
  • Check empty arrays before reading the first element.

Why array bounds fail in Java programs

ArrayIndexOutOfBoundsException happens when code asks an array for a position that does not exist. Java arrays start at index 0, so the last valid index is always length minus one. The exception is useful because it stops the program at the exact unsafe access instead of returning random memory or hiding the bug.

This error usually appears in loops, manual index calculations, user-selected positions, and code that assumes two arrays have the same length. To debug it, inspect the index, the array length, and the loop condition at the moment of failure. The fix is not just to subtract one blindly; the real fix is to make the access rule match the valid index range.

  • Use i < array.length, not i <= array.length, when walking the whole array.
  • Validate user-provided indexes before reading or writing.
  • Check nested loops carefully because the inner index may belong to a different array.
  • Prefer enhanced for loops when the position number is not needed.

Read the Stack Trace and Prove the Boundary

The exception message identifies the invalid index and the array length; the first application frame in the stack trace identifies the access that failed. For an array of length n, only indexes 0 through n - 1 are valid. An index equal to length is already outside the array.

Write the boundary before changing the loop. Forward traversal uses index < array.length. Reverse traversal starts at array.length - 1 and continues while index >= 0. For neighboring access such as values[index + 1], stop one element earlier.

  • Confirm whether the invalid value is the loop counter, parsed user input, or a calculated offset.
  • Log the index and length together when the failing state is difficult to reproduce.
  • Check empty arrays before reading element 0 or length - 1.
  • Test the smallest sizes: empty, one element, and the first size that enters every branch.

Prevent Invalid Indexes at API Boundaries

Validate an index when it crosses a trust boundary, not before every internal access. A method receiving a menu choice, file position, or client-supplied offset should reject values below zero or greater than or equal to the collection size with a clear domain message.

Prefer enhanced for loops and stream operations when the algorithm does not need an index. When it does, keep the index calculation close to the access and document whether an upper bound is inclusive or exclusive. Catching ArrayIndexOutOfBoundsException is not a substitute for validating normal input.

Validate before indexing

Validate before indexing
static String itemAt(String[] items, int index) {
    if (items.length == 0) {
        throw new IllegalArgumentException("items must not be empty");
    }
    if (index < 0 || index >= items.length) {
        throw new IllegalArgumentException(
            "index must be between 0 and " + (items.length - 1)
        );
    }
    return items[index];
}

The public method reports an input-contract error before the JVM reaches the array access.

ArrayIndexOutOfBoundsException in Java Fix Example

ArrayIndexOutOfBoundsException in Java Fix Example
public class Demo {
    public static void main(String[] args) {
        System.out.println("Practice ArrayIndexOutOfBoundsException in Java Fix");
    }
}

Wrong and Correct Loop Boundary

Wrong and Correct Loop Boundary
int[] marks = {80, 75, 90};

// Wrong: i becomes 3, but the last valid index is 2.
// for (int i = 0; i <= marks.length; i++) {}

for (int i = 0; i < marks.length; i++) {
    System.out.println(marks[i]);
}

Safe array access with a boundary check

Safe array access with a boundary check
int[] scores = {64, 78, 91};
int requestedIndex = 3;

if (requestedIndex >= 0 && requestedIndex < scores.length) {
    System.out.println(scores[requestedIndex]);
} else {
    System.out.println("Index is outside the valid range");
}
Before you move on

ArrayIndexOutOfBoundsException in Java Fix: Causes and Fixes Mastery Check

5 checks
  • It happens when code asks for an index that is negative or greater than the last valid index.
  • When you debug it, print or inspect three values together: the array length, the current index, and the loop condition.
  • The most common cause is using.
  • If those three values are clear, the fix is usually obvious.
  • ArrayIndexOutOfBoundsException happens when code asks an array for a position that does not exist.
Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.