Quick Answer
Handle invalid array access.
Understanding the Issue
This runtime exception occurs when accessing an array with an invalid 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
// Check bounds:
int index = 5;
if (index >= 0 && index < arr.length) {
val = arr[index];
}
// Enhanced for-loop (avoids indexes):
for (int num : arr) {
// Safe iteration
}
// Use List instead:
List<Integer> list = Arrays.asList(1, 2, 3);
if (index < list.size()) {
val = list.get(index);
}
// Java 9+:
OptionalInt val = Arrays.stream(arr)
.skip(index)
.findFirst();
Key Takeaways
Always validate array indices before access.