How to avoid ArrayIndexOutOfBoundsException in Java?


For below code ArrayIndexOutOfBoundsException is occurring:

public class Example {  
    public static void main(String[] args) {  
String[] arr = {"a","b","c","d"};   
//Declaring 4 elements in the String array                                       
        for(int i=0;i<=arr.length;i++) {       
//Here, no element is present at the iteration number arr.length, i.e 4  
//So it will throw ArrayIndexOutOfBoundException at iteration 4           

The ArrayIndexOutOfBoundsException in Java occurs whenever someone try 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.

We can avoid this exception by using a type-safe Iterator. These are the iterators which allow modifications of a collection while iterating over it.

HashMap map = new HashMap<>();  
final Iterator it = map.Keyset().iterator();  
for (int i = 0; it.hasNext(); i++)  


Related #tags:     #java     #exception     #core-java    

Related questions

Looking for change? Click below to prepare for technical interview.

Technical Interview Questions