Fix ArrayIndexOutOfBoundsException and IndexOutOfBounds
Read the index and length in the exception, find the off-by-one or empty-input bug that caused it and fix it for arrays, lists and strings.

ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 is among the most precise error messages Java produces. It names the index used and the length of the array, and the stack trace beneath it names the line. Fixing it is rarely a hunt: the message tells you the code touched an element that does not exist, and the work is deciding why the index was wrong. This post covers the causes in the order they occur: the off-by-one loop, empty input, index arithmetic, strings and split, and the related IndexOutOfBoundsException from lists. It ends with a test that makes the failure obvious. It uses JDK 25, where the message format described here has been stable since JDK 11.
Reading the message
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at com.example.Report.total(Report.java:14)
at com.example.Main.main(Main.java:7)Valid indexes for an array of length 5 are 0 to 4. An index of 5 is one past the end, and a negative index such as -1 produces Index -1 out of bounds for length 5. The first frame under the exception is the line that did the access, and the second is who called it. Read both: the faulty value is often computed one call up, and the access line only reveals it. How to read a trace systematically is in reading a Java stack trace.
For a List, the exception is IndexOutOfBoundsException (or ArrayIndexOutOfBoundsException when an ArrayList is backed by an array and the check fails inside the JDK), with the message Index 3 out of bounds for length 3. The cause and the fix are the same.
The off-by-one loop
The classic: a loop that runs one step too far.
static int total(int[] values) {
int sum = 0;
for (int i = 0; i <= values.length; i++) { // <= reads values[values.length]
sum += values[i];
}
return sum;
}i <= values.length visits index 5 of a five-element array. The fix is <. Better, avoid the index when you do not need it:
for (int value : values) {
sum += value;
}An enhanced for loop cannot go out of bounds, and Arrays.stream(values).sum() is shorter still. Keep indexed loops for the cases where the position matters, such as comparing neighbours, and in those cases write the bounds as a deliberate statement: for (int i = 1; i < values.length; i++) compares values[i - 1] with values[i] and cannot fail on an array with at least one element.
The reverse loop has its own form: for (int i = values.length; i >= 0; i--) starts one too high and ends one too low. for (int i = values.length - 1; i >= 0; i--) is the correct pair.
Empty input
Code that works on every test array fails on the empty one:
int first = args[0].length(); // fails with "Index 0 out of bounds for length 0"
double average = values[values.length / 2]; // median of an empty arrayIndex 0 of an empty array does not exist. main(String[] args) is empty when no command-line arguments are given, which is how many tools crash on first run. Check the length before indexing, and decide what an empty input means: an error with a clear message, a default value, or an Optional.
if (args.length == 0) {
System.err.println("usage: report <file>");
System.exit(2);
}Empty collections arrive from places you did not expect: a query that returned no rows, a file with only a header, a request with no body, a split of an empty string. Treat the empty case as a first-class input in every method that indexes, and test it.
Index math that goes wrong
Computed indexes fail in ways that hide the real bug. A circular buffer with buffer[(head + 1) % size] fails when size is zero (a different exception) and when head is negative, because % in Java keeps the sign of the dividend: -1 % 5 is -1, not 4. Use Math.floorMod(head - 1, size) for wrap-around that is always non-negative.
A hash index computed from hashCode() % buckets.length can be negative, since hashCode() can be negative; the same fix applies, or mask with & (buckets.length - 1) for power-of-two sizes. Binary search code with (low + high) / 2 can overflow for very large arrays and go negative, which is why (low + high) >>> 1 is the safe form, and Arrays.binarySearch already uses it. Off-by-one in a two-dimensional array is a common variant: grid[row][col] with row and col swapped when the grid is not square raises the exception for the shorter dimension, so check which length each index is tested against.
Arrays that grow or shrink while you iterate are another source: removing elements while a counting loop continues leaves the loop bound stale. Loop over the live length, or collect indexes first and remove afterwards. For collections the failure is a different exception, ConcurrentModificationException.
Strings
Strings produce the same error under different names: StringIndexOutOfBoundsException from charAt, substring and String.valueOf(char[], ...). And split is the biggest source of array-index errors in everyday code:
String[] parts = line.split(",");
String name = parts[0];
String city = parts[2]; // fails if the line has fewer than three fields"a,b".split(",") returns two elements, so parts[2] fails. Trailing empty strings are removed by default: "a,b,,".split(",") has two elements, not four; use split(",", -1) to keep them. An empty line split returns an array of one empty string. Validate the number of fields before indexing, and report the line number in the error so the bad row can be found:
if (parts.length < 3) {
throw new IllegalArgumentException("line " + lineNo + ": expected 3 fields but got " + parts.length);
}For CSV, use a real parser: quoted fields with commas defeat split. Similarly, substring(0, 10) on a string shorter than ten characters throws; use Math.min(10, s.length()) or the String.substring guard s.length() > 10 ? s.substring(0, 10) : s.
Make the failure obvious in a test
Test the boundaries, because that is where the index goes wrong: the empty array, a single element, the exact length and one past it.
@ParameterizedTest
@MethodSource("boundaries")
void total_handles_boundary_sizes(int[] values, int expected) {
assertEquals(expected, Report.total(values));
}
static Stream<Arguments> boundaries() {
return Stream.of(
Arguments.of(new int[] {}, 0),
Arguments.of(new int[] {7}, 7),
Arguments.of(new int[] {1, 2}, 3),
Arguments.of(new int[] {1, 2, 3, 4, 5}, 15));
}Boundary cases are cheap to write and catch the whole family. A failing test for the empty array is also the clearest bug report. More on parameterized tests is in the JUnit 5 handbook.
Where this does not apply
If the stack trace points into library code, the library was handed an index or a length it did not accept, usually from your arguments: System.arraycopy with a wrong length, Arrays.copyOfRange with a start beyond the end, or List.subList with bad bounds. The message names the bad value; trace it back to your call. Reading about a failure like this in the JDK's own documentation is faster than guessing: see the exception Javadoc, and for the null-safe helpers in Objects, the Objects Javadoc, including Objects.checkIndex, which throws the standard exception for a bad index and is the right tool for validating indexes in your own methods.


