What causes a java.lang.ArrayIndexOutOfBoundsException and How to prevent it?

When trying to access an Array value at an undefined index, we will get the ArrayIndexOutOfBoundsException. To prevent this error we should access the values at a defined index only. In that if an Array has 3 elements the defined indexes will be 0,1,2. Any other index say 4 will be undefined.

Example:

public class ArrayIndexOutOfBoundsExceptionExample {

public static void main(String args[]) {
int intArray[] = new int[5];

intArray[0] = 1;
intArray[1] = 2;
intArray[3] = 3;
intArray[4] = 4;
intArray[5] = 5; //ArrayIndexOutOfBoundsException

for (int i = 0; i <= intArray.length; i++) {
      System.out.println(intArray[i]);
      }
    }
}

 

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at nlpexamples.ArrayIndexOutOfBoundsExceptionExample.main(ArrayIndexOutOfBoundsExceptionExample.java:21)
Java Result: 1

 

To prevent ArrayIndexOutOfBoundsException , we have to assign the values defined allocated memory index only.

Example: If we allocated 5 , array index start from 0 index value to we have to assign the values 0,1,2,3 and 4 indexes.

Example:

public class ArrayIndexOutOfBoundsExceptionSolved {

public static void main(String args[]) {
int intArray[] = new int[5];

for (int i = 0; i < intArray.length; i++) {
    intArray[i] = i;
}

for (int i = 0; i < intArray.length; i++) {
    System.out.println(intArray[i]);  
      }
   }
}

Output:

0
1
2
3
4

 

Happy Coding :).

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s