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  
             System.out.println(arr[i]);      
//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<>();  
map.put(1,1);  
map.put(2,2);  
map.put(3,3);  
map.put(4,4);  
  
final Iterator it = map.Keyset().iterator();  
for (int i = 0; it.hasNext(); i++)  
{  
    System.out.println(it.next());  
} 

 


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

Related questions




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


Technical Interview Questions