Accessing an array with an index that is out of its valid range.
This exception is thrown when you try to access an array element using an index that is either negative or greater than or equal to the array's length. Java arrays are fixed-size and 0-indexed, so an array of length `n` has valid indices from `0` to `n-1`.
Common causes: using `<=` instead of `<` in a loop condition, hardcoding array indices that may change, off-by-one errors when computing indices, iterating one past the end of the array, or using an index derived from user input without validation.
1public class Main {2 public static void main(String[] args) {3 int[] numbers = {10, 20, 30, 40, 50};4 5 // Bug: loop goes up to numbers.length (5), but valid indices are 0-46 for (int i = 0; i <= numbers.length; i++) {7 System.out.println(numbers[i]);8 }9 }10}1public class Main {2 public static void main(String[] args) {3 int[] numbers = {10, 20, 30, 40, 50};4 5 // Fix 1: Use strict less-than (<)6 for (int i = 0; i < numbers.length; i++) {7 System.out.println(numbers[i]);8 }9 10 // Fix 2: Use enhanced for-each loop (preferred when index isn't needed)11 for (int number : numbers) {12 System.out.println(number);13 }14 15 // Fix 3: Validate index before access16 int index = 5;17 if (index >= 0 && index < numbers.length) {18 System.out.println(numbers[index]);19 } else {20 System.out.println("Index " + index + " is out of bounds.");21 }22 }23}Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
The array has 5 elements at indices `0` through `4`. The loop condition `i <= numbers.length` allows `i` to reach `5` (equal to `numbers.length`). When `numbers[5]` is accessed, Java throws `ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5`.