Friday, October 30, 2009

Published 10/30/2009 by with 0 comment

java.lang.ArrayIndexOutOfBoundsException


It's a very common runtime error message or exception we face when we use array wrongly. Very specifically this exception is thrown to indicate that an array has been accessed with an illegal index (location / position / subscript). The index is either negative or greater than or equal to the size of the array.


See the following code:

int data[]={5,7,18,21,27,15,3};

//show the array elements
for(int i=0;i<=7;i++)
{
System.out.println(data[i]);
}

Here the array size is 7 as the array is initialized by assigning 7 elements {5,7,18,21,27,15,3}. So the valid array index is 0 to 6. In the loop condition, we have given i&lt=7 and i is used as the array index inside the loop - so when i is 7 it tries to access the array element 7 but 7 is not a valid index. This causes the exception. Correct loop condition is i<7 or i<=6. The recommended approach is using the array built in variable length instead of the static size. Correct the code as below:


int data[]={5,7,18,21,27,15,3};

//show the array elements
for(int i=0;i<data.length;i++)//data is the array name
{
System.out.println(data[i]);
}

    email this       edit

0 comments:

Post a Comment