ArrayIndexOutOfBoundsException in Java
The ArrayIndexOutOfBoundsException occurs whenever we are trying to access any item of an array at an index which is not present in the array. In other words, the index may be negative or exceed the size of an array.
The ArrayIndexOutOfBoundsException is a subclass of IndexOutOfBoundsException, and it implements the Serializable interface.
Example of ArrayIndexOutOfBoundsException
Constructors of ArrayIndexOutOfBoundsException
The following types of ArrayIndexOutOfBoundException constructors are -
||It constructs ArrayIndexOutOfBoundsException with no details being showed up in the console.
||It constructs ArrayIndexOutOfBoundsException with the index variable indicating the index which is illegal
||It constructs ArrayIndexOutOfBoundsException with specified detail message.
How to avoid ArrayIndexOutOfBoundsException
- One of the biggest issues due to which ArrayIndexOutOfBoundsException occurs is that the indexing of array starts with 0 and not 1 and the last element is at the array length -1 index, due to which, users commonly make a mistake while accessing the elements of the array.
- Always take care while making the starting and end conditions of the loop.
- If stuck with any such exception, try to debug the code.
- Using an enhanced for loop
- An enhanced for loop is the one which iterates over contiguous memory allocation and iterates only on legal indexes.
- Using a type-safe Iterator
- Type-safe iterators don't throw an exception when they are iterating over a collection and making changes to it as they make a snapshot of the collection and make the changes to it. For example-