Understanding Array IndexOutofbounds Exception in Java

1.5

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++)
          System.out.println(ar[i]);
    }
}

Runtime error throws an Exception:

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

Output:

1
2
3
4
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<>();
        lis.add("My");
        lis.add("Name");
        System.out.println(lis.get(2));
    }
}

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

This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

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

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1.5 Average Difficulty : 1.5/5.0
Based on 31 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.