java.lang.ArrayIndexOutOfBoundsException
java.lang.ArrayIndexOutOfBoundsException in Java means your Java code attempted to access an array with an illegal index that is either negative or greater than or equal to the array length.
How do I fix java.lang.ArrayIndexOutOfBoundsException?
To fix java.lang.ArrayIndexOutOfBoundsException in Java, locate the line causing the error and check the values right before it runs. Most occurrences happen because of using <= arr.length in a standard for-loop condition. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.
What does java.lang.ArrayIndexOutOfBoundsException mean?
The Java Virtual Machine (JVM) checks array boundaries on every indexing operation. When code accesses arr[i] where i < 0 or i >= arr.length, the JVM throws ArrayIndexOutOfBoundsException at runtime.
Why does java.lang.ArrayIndexOutOfBoundsException happen?
1. Using <= arr.length in a standard for-loop condition
An array of size N has indices 0 through N-1. When i equals arr.length, the final iteration crashes.
Breaks
for (int i = 0; i <= arr.length; i++) {
System.out.println(arr[i]); // crashes on last pass!
}Works
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}2. Accessing index 0 on an empty array
If the array has length 0, even index 0 is out of bounds.
Breaks
int first = numbers[0]; // crashes if numbers is empty!Works
if (numbers.length > 0) {
int first = numbers[0];
}How to find it in your own code
Ensure loop conditions use strict inequality i < arr.length. Use the enhanced for-loop (for (int x : arr)) when indices are not strictly required. Verify array length > 0 before accessing fixed indices.
Try it: fix this bug
easyjava.lang.StringIndexOutOfBoundsException: String index out of range: 5
public class Main {
public static String extractPrefixSafely(String text) {
// substring throws StringIndexOutOfBoundsException if endIndex > length
return text.substring(0, 5);
}
public static void main(String[] args) {
System.out.println(extractPrefixSafely("abc"));
}
}Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.