ArrayIndexOutOfBoundsException is an exception, thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
illegal index in java is index value less than zero or -ve values and index value equal to or greater than array length. Read here
For example:
int[] data = new int[5]; int i = data[5]; // Throws the exception
In above code array of int is initialize for 5 elements, means array length is 5. When the array is accessed with index 5 then it will throw an ArrayIndexOutOfBoundsException
. In Java array index start from 0, so in an array of length 5, the max index will be 4.
To avoid this always check that index is greater than -1 and should be less than array length.
While iterating array then always check as given below
int[] data = new int[5]; for (int j = 0; j < data.length; j++) { //Something }
Or you can iterate using for each
int[] data = new int[5]; for (int i : data) { //Something }
ArrayIndexOutOfBoundsException is also caused by ArrayList object, or any collection object which is accessed by index.
public static void main(String[] args) { List data = new ArrayList<>(); data.add(0); data.add(2); int r = data.get(-1); r = data.get(100); }
above code will throw an exception as given below
java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.ArrayList.elementData(ArrayList.java:422) at java.util.ArrayList.get(ArrayList.java:435) at ArrayIndex.main(ArrayIndex.java:19)
Finally to avoid ArrayIndexOutOfBoundsException, just check array accessing index fall between 0 and array.length-1. and suppose you are exposing some method in your class which accesses the array by in parameter as index, then you should also expose a method which returns length or size of your underlying array. So that call can check in parameter before calling the method.