← Debugging Guides

阅读中文版本

Java ArrayIndexOutOfBoundsException — Wrong Array Index

Fix ArrayIndexOutOfBoundsException by checking array length before access, using loop bounds < length, and preferring enhanced for or collections.

beginnerdebuggingjavaexceptionsarrays

Symptoms

  • Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
  • The stack trace points exactly at the array access line
  • The error appears only for short inputs

Possible causes

  • A loop uses index <= array.length instead of <
  • The off-by-one comes from a 1-based calculation applied to a 0-based array
  • The array length differs from the assumed row length in a jagged or ragged array

Diagnosis steps

Read the exact index and length from the message

java -cp target/classes com.example.Main 2>&1 | grep OutOfBounds

Interpretation

The message gives index and length, which immediately shows the off-by-one.

Audit loop bounds

grep -rn "<= *.length\|length *+ *1" src/main/java

Interpretation

Every <= length or length+1 index expression is a candidate for the boundary bug.

Root cause

Java arrays are zero-indexed and bounds-checked at access. Any index below 0 or at or above length throws ArrayIndexOutOfBoundsException, most often from an off-by-one loop bound.

Fix

Use i < array.length, iterate with enhanced for when the index is not needed, and guard the first/last element access with a length check.

Risk note

Wrapping in try/catch to swallow the exception hides a real logic error; fix the index instead.

Verify the fix

Rerun with the previously failing input and confirm no exception; add tests for empty and single-element arrays.

Symptoms

When you hit “Java ArrayIndexOutOfBoundsException — Wrong Array Index”, guessing wastes time. The guide below follows evidence: reproduce the symptom, run targeted diagnostics, identify the root cause, apply the fix, and verify it with concrete checks.

Observed symptoms include:

  • Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
  • The stack trace points exactly at the array access line
  • The error appears only for short inputs

Reproduce and Diagnose

Reproduce the failure in isolation before changing any code. Work through the checks below in order; each one narrows the search space.

Step 1: Read the exact index and length from the message

java -cp target/classes com.example.Main 2>&1 | grep OutOfBounds

The message gives index and length, which immediately shows the off-by-one.

Step 2: Audit loop bounds

grep -rn "<= *.length\|length *+ *1" src/main/java

Every <= length or length+1 index expression is a candidate for the boundary bug.

Likely contributors, in order of frequency:

  • A loop uses index <= array.length instead of <
  • The off-by-one comes from a 1-based calculation applied to a 0-based array
  • The array length differs from the assumed row length in a jagged or ragged array

Root Cause

Java arrays are zero-indexed and bounds-checked at access. Any index below 0 or at or above length throws ArrayIndexOutOfBoundsException, most often from an off-by-one loop bound.

The Fix

Use i < array.length, iterate with enhanced for when the index is not needed, and guard the first/last element access with a length check.

Watch out: Wrapping in try/catch to swallow the exception hides a real logic error; fix the index instead.

int[] values = getValues();

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

// avoid indexing when iterating
for (int v : values) {
    System.out.println(v);
}

// guard first element
if (values.length > 0) {
    System.out.println(values[0]);
}

Verify and Prevent

Rerun with the previously failing input and confirm no exception; add tests for empty and single-element arrays.

Once verified, add a regression test that reproduces the original symptom so the failure cannot silently return.

This class of failure is usually environmental rather than pure logic, so capture the exact command, the environment variables, and the working directory in your bug report. Reproduce it in the smallest possible script, then widen the scope only once the minimal case is understood. A short written checklist for this failure mode saves hours the next time it appears.