Why This Happens
Java arrays are zero-indexed, so an array of length 5 has valid indices 0 through 4. Accessing index 5 or any negative index throws this exception. This commonly happens in off-by-one errors in loops.
The Problem
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i <= arr.length; i++) {
System.out.println(arr[i]); // Fails when i == 5
}The Fix
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}Step-by-Step Fix
- 1
Identify the out-of-bounds index
Read the exception message to see which index was used and what the array length is.
- 2
Check loop boundaries
Look for off-by-one errors. Use < arr.length instead of <= arr.length in loop conditions.
- 3
Validate index before access
Add bounds checking before accessing the array, especially if the index comes from user input or a calculation.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free