<code>ArrayIndexOutOfBoundsException</code> in Java
ArrayIndexOutOfBoundsException is thrown when you access an array element with an index < 0 or >= array.length. It's an unchecked exception β always a programming bug, never a condition to catch.
What the error looks like
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
The classic off-by-one
int[] arr = new int[5];
for (int i = 0; i <= arr.length; i++) { // β <= β goes one past the end
arr[i] = i;
}
for (int i = 0; i < arr.length; i++) { // β
<
arr[i] = i;
}
for (int x : arr) { ... } // β
for-each β no index at all
Negative indices
int[] a = {1, 2, 3};
a[-1]; // ArrayIndexOutOfBoundsException
a[a.length - 1]; // β
last element
For lists: IndexOutOfBoundsException
List.get(index) throws IndexOutOfBoundsException, a different class. Same underlying bug, different type:
List<String> xs = List.of("a", "b");
xs.get(5); // IndexOutOfBoundsException: Index 5 out of bounds for length 2
Safe alternatives
// for-each skips the index entirely
for (String s : xs) System.out.println(s);
// Streams
xs.stream().forEach(System.out::println);
// Get-or-default
String s = i < xs.size() ? xs.get(i) : "default";
Common mistakes
- Loop condition
<=instead of<β the most common off-by-one. - Using
arr.length()β arrays have alengthfield, not method. Strings use.length(), collections use.size(), arrays use.length. - Passing an unchecked user input as an index β validate at the boundary.
Related
Pillar: Java exceptions. See also for loops and ArrayList.