Understanding Array IndexOutofbounds Exception in Java

Java supports creation and manipulation of arrays, as a data structure. The index of an array is an integer value that has value in interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to size of array is made, then the JAVA throws a ArrayIndexOutOfBounds Exception. This is unlike C/C++ where no index of bound check is done.

The ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program.

// A Common cause index out of bound
public class NewClass2
    public static void main(String[] args)
        int ar[] = {1, 2, 3, 4, 5};
        for (int i=0; i<=ar.length; i++)

Runtime error throws an Exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
	at NewClass2.main(NewClass2.java:5)



Here if you carefully see, the array is of size 5. Therefore while accessing its element using for loop, the maximum value of index can be 4 but in our program it is going till 5 and thus the exception.

Let’s see another example using arraylist:

// One more example with index out of bound
import java.util.ArrayList;
public class NewClass2
    public static void main(String[] args)
        ArrayList<String> lis = new ArrayList<>();

Runtime error here is a bit more informative than the previous time-

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
	at java.util.ArrayList.rangeCheck(ArrayList.java:653)
	at java.util.ArrayList.get(ArrayList.java:429)
	at NewClass2.main(NewClass2.java:7)

Lets understand it in a bit of detail-

  • Index here defines the index we are trying to access.
  • The size gives us information of the size of the list.
  • Since size is 2, the last index we can access is (2-1)=1, and thus the exception

The correct way to access array is :

for (int i=0; i<ar.length; i++) 

Handling the Exception:

  • Use for-each loop: This automatically handles indices while accessing the elements of an array. Example-
    for(int m : ar){
  • Use Try-Catch: Consider enclosing your code inside a try-catch statement and manipulate the exception accordingly. As mentioned, Java won’t let you access an invalid index and will definitely throw an ArrayIndexOutOfBoundsException. However, we should be careful inside the block of the catch statement, because if we don’t handle the exception appropriately, we may conceal it and thus, create a bug in your application.

Quiz Question

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment



load comments

Subscribe to Our Newsletter