Sunday, May 15, 2011

How to deal with ArrayIndexOutOfBoundsException



The name itself indicates that this exception is thrown if an attempt is made to access the array elements with an illegal index. Illegal indices are those which exceeds the size of array or which are negative. Here is an example to demonstrate the ArrayIndexOutOfBounds Exception.

class ArrayIndexOutOfBoundsExceptionDemo1
{
public static void main(String[] args)
{
int[] array=new int[]{1,2,3,4,5};
int i=0;

System.out.println(array[0]);
System.out.println(array[1]);
System.out.println(array[2]);
System.out.println(array[3]);
System.out.println(array[4]);
System.out.println(array[5]);
}
}

The above code will produce output like this:



1
2
3
4
5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
        at ArrayIndexOutOfBoundsExceptionDemo1.main(ArrayIndexOutOfBoundsExcepti
onDemo1.java:13)

Press any key to continue...


This means everything was OK till the index of element which was being accessed was less than the size of array. As soon as the index becomes equal to or greater than the size of the array an exception is thrown. As the array index starts with 0, in the above code we can access elements till the index is between 0 and 4. As soon as we try to access the element with the index 5, an exception is thrown. This will also happen if we inset the below statement in the above code:


System.out.println(array[-1]);

This is because -1 is not a valid array index.

Whenever the 
ArrayIndexOutOfBoundsException is thrown, then get the stack trace and try to see where the constraints on array index are being violated. This will help you to troubleshoot the problem.

No comments:

Post a Comment