Quick Answer
Handle invalid array access.
Understanding the Issue
This exception occurs when trying to access an array with an illegal index (negative or ? array length).
The Problem
This code demonstrates the issue:
Java
Error
int[] arr = new int[5];
int val = arr[5]; // Throws
The Solution
Here's the corrected code:
Java
Fixed
// Solution 1: Check bounds before access
int index = 5;
if (index >= 0 && index < arr.length) {
val = arr[index];
}
// Solution 2: Enhanced for loop
for (int num : arr) {
// Safe iteration
}
// Solution 3: Use List instead
List<Integer> list = Arrays.asList(1, 2, 3);
if (index < list.size()) {
val = list.get(index);
}
// Solution 4: Array utility methods
int safeGet(int[] array, int index) {
return (index >= 0 && index < array.length) ? array[index] : 0;
}
Key Takeaways
Always validate array indices before access.