πŸ”§ Error Fixes
Β· 1 min read

Java: ArrayIndexOutOfBoundsException β€” How to Fix It


ArrayIndexOutOfBoundsException: Index X out of bounds for length Y means you’re accessing index X in an array that only has Y elements (indices 0 to Y-1).

Why this happens

Java arrays are zero-indexed and have a fixed length. When you access an index that’s negative or greater than or equal to the array length, the JVM throws this exception at runtime. Unlike C/C++, Java performs bounds checking on every array access to prevent memory corruption.

What causes this error

  1. Off-by-one error β€” using <= instead of < in a loop
  2. Empty array β€” accessing index 0 on an empty array
  3. Hardcoded index β€” assuming the array has at least N elements

Fix 1: Fix the loop boundary

// ❌ Off-by-one β€” arrays are 0-indexed
for (int i = 0; i <= arr.length; i++) { // crashes on last iteration
    System.out.println(arr[i]);
}

// βœ… Use < not <=
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}

// βœ… Or use enhanced for loop
for (String item : arr) {
    System.out.println(item);
}

Fix 2: Check length before accessing

// ❌ Crashes if array is empty
String first = arr[0];

// βœ… Check first
if (arr.length > 0) {
    String first = arr[0];
}

Alternative solutions

Use Arrays.stream() for safe processing β€” streams handle empty arrays gracefully:

String first = Arrays.stream(arr).findFirst().orElse("default");

Use ArrayList instead β€” it throws a clearer IndexOutOfBoundsException and has .isEmpty(), .size(), and .get() with bounds checking.

Prevention

  • Prefer enhanced for-loops or streams over manual index management to eliminate off-by-one errors.
  • Always validate external input (like command-line args) length before accessing specific indices.

Related: Java: NullPointerException fix Β· Java: ClassNotFoundException fix