ArrayIndexOutOfBoundsException
JavaFATALCommonArray
Array index out of bounds
Quick Answer
Check array.length before indexing, or use enhanced for-loop to avoid manual indexing.
What this means
Thrown when code tries to access an array element with an index that is negative or >= array.length.
Why it happens
- 1Index equals array.length (off-by-one)
- 2Negative index from a subtraction result
Fix
Bounds check before access
Bounds check before access
if (i >= 0 && i < arr.length) {
System.out.println(arr[i]);
}Why this works
Explicit range guard prevents the JVM from throwing the exception.
Code examples
Triggerjava
int[] a = {1, 2, 3};
int x = a[3]; // ArrayIndexOutOfBoundsExceptionSafe accessjava
int get(int[] a, int i) {
return (i >= 0 && i < a.length) ? a[i] : -1;
}Use List insteadjava
List<Integer> list = List.of(1, 2, 3); // list.get(3) throws IndexOutOfBoundsException with better message
Same error in other languages
Sources
Official documentation ↗
Java SE Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev