java.lang.ArrayIndexOutOfBoundsException
ID: java/arrayindexoutofboundsexception
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 17 | active | — | — | — |
Root Cause
ArrayIndexOutOfBoundsException is thrown when code accesses an array element with an index that is negative or greater than or equal to the array length. The error message includes the invalid index value.
genericWorkarounds
-
95% success Check the array length before accessing and fix the loop boundary or index computation
1. Read the error message to find the invalid index and the file:line where it occurred. 2. Check loop boundaries: use 'i < array.length' not 'i <= array.length' (off-by-one). 3. For direct access: validate 'index >= 0 && index < array.length' before accessing. 4. Common causes: empty array from unexpected input, concurrent modification of shared array, String.split() returning fewer parts than expected. 5. Consider using a List<T> instead of arrays for dynamic sizing.
-
90% success Use Collections (ArrayList, List) instead of arrays for dynamic data, and use List utility methods for safe access
1. Replace arrays with ArrayList<T> for dynamic sizing. 2. Use list.isEmpty() checks before accessing elements. 3. For getting the last element safely: list.get(list.size() - 1) with a size check, or use Guava's Iterables.getLast(list, defaultValue). 4. Use ListIterator for safe indexed iteration. 5. For fixed-size indexed data, use EnumMap or a Map<Integer, T> to avoid index-based bugs.
Dead Ends
Common approaches that don't work:
-
Catching ArrayIndexOutOfBoundsException to return a default value instead of fixing the indexing logic
75% fail
Using try-catch for array bounds is an anti-pattern in Java. Exceptions are expensive to create (stack trace capture), and this approach hides logic bugs. The incorrect index indicates a flaw in the algorithm — a loop boundary error, an off-by-one error, or an assumption about data size that is violated.
-
Pre-allocating a very large array to avoid bounds issues
70% fail
Over-allocating arrays wastes memory and does not fix the indexing logic. If the index is computed incorrectly (e.g., negative, or based on wrong input), a larger array only raises the threshold before failure without fixing the root cause. It can also cause OutOfMemoryError.