Quick Answer
Handle invalid array access attempts.
Understanding the Issue
Thrown when accessing negative indexes or indexes >= array length. Common in loops with incorrect termination conditions.
The Problem
This code demonstrates the issue:
Java
Error
int[] arr = new int[5];
int val = arr[5]; // Throws (valid indexes 0-4)
The Solution
Here's the corrected code:
Java
Fixed
// Solution 1: Proper bounds checking
if (index >= 0 && index < arr.length) {
val = arr[index];
}
// Solution 2: Enhanced for loop
for (int num : arr) { // Safely iterates all elements
System.out.println(num);
}
// Solution 3: Use List instead
List<Integer> list = Arrays.asList(1, 2, 3);
Integer safeGet = list.get(index); // Throws IndexOutOfBounds
Key Takeaways
Always validate array indexes before access.