Friday, 26 August 2016

Common reasons of java.lang.ArrayIndexOutOfBoundsException in Java

Reasons of java.lang.ArrayIndexOutOfBoundsException 

java.lang.ArrayIndexOutOfBoundsExcepiton is one of the most common errors in Java program. It occurs when Java program tries to access an invalid index e.g. an index which is not positive or greater than the length of an array. For example, if you have an array of String e.g. String[] name = {"abc"} then trying to access name[1] will give java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 error because index 1 is invalid here. Why? because index in Java array starts with zero rather than 1, hence in an array of just one element the only valid index is index zero.  This was one of the most common scenarios which cause several million of ArrayIndexOutOfBoundsException daily. Sometimes it just a plain programming error but sometimes if an array is populated outside and if there is an error on feed than also you get java.lang.ArrayIndexOutOfBoundsException in Java.

In this article, I will share with you some of the common reasons of ArrayIndexOutOfBoundsExcpetion and their solution. This will give you enough experience to deal with this error in future.

In order to solve ArrayIndexOutOfBoundsException, just remember following key details about array in Java:

1) The array index in Java starts at zero and goes to length - 1, for example in an integer array int[] primes = new int[10], the first index would be zero and last index out be 9 (10 -1)

2) Array index cannot be negative, hence prime[-1] will throw java.lang.ArrayIndexOutOfBoundsException.

3) The maximum array index can be Integer.MAX_VALUE -1 because the data type of index is int in Java and the maximum value of int primitive is Integer.MAX_VALUE. See Big Java: Early Objects, 5th edition by Cay S. Horstmann to learn more about array data structure in Java. 

Now, let's see some of the common examples of ArrayIndexOutOfBoundsException in Java

java.lang.ArrayIndexOutOfBoundsException

length=0 index=0

This is the classic case of accessing an empty array. Since length is zero it means the array is empty and the index is zero means we are trying to access the first element of the array. This happens when you try to access an array without checking its length, as shown below.
public class Test {

  public static void main(String[] args) {

    int[] array = new int[0];

    // bad code
    int number = array[0];

    // good code
    if (array.length > 0) {
      number = array[0];
    }
  }

}

When you run this program you will get following error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Test.main(Main.java:15)

A solution to this problem is to always access array after checking array length, as shown in the good code snippet.





java.lang.ArrayIndexOutOfBoundsException: length=1; index=1

This the second most popular reason of ArrayIndexOutOfBoundsException in Java. Here you are trying to access an array by its length. If you remember, the maximum valid index in the array is length -1 but if you somehow try to access index = length then you get this error. This usually happens when you use <= or >= sign in for loop while looping over an array in Java.
public class ABC {

  public static void main(String[] args) {

    int[] array = new int[10];
    int sum = 0;

    // bad code
    for (int i = 0; i <= array.length; i++) {
      sum = sum + array[i];
    }

    // good code
    for (int i = 0; i < array.length; i++) {
      sum = sum + array[i];
    }
  }

}

If you run this code, you will get following error :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at ABC.main(Main.java:16)

This is because 10 is not a valid index for an array of length 10. The valid index is only from 0 to 9. See a good data structure book e.g. Introduction to Algorithm to learn more about array data structure in general.



java.lang.ArrayIndexOutOfBoundsException length=12 index=-1
This is the third common reasons of millions of ArrayIndexOutOfBoundsException. In this case, you are trying to access the array using a negative index. There could be different reasons why index becomes negative but the bottom line is you should not access an array with the negative index.

That's all about 3 examples of ArrayIndexOutOfBoundsException in Java. You can solve this error very easily If you remember the key details about array implementation in Java e.g. array index starting at zero and no negative indexes are allowed. You should also know that the maximum an index can go up to Integer.MAX_VALUE value because the data type of index is int in Java.

No comments:

Post a Comment