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
- Off-by-one error β using
<=instead of<in a loop - Empty array β accessing index 0 on an empty array
- 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