Java ArrayIndexOutOfBoundsException – Causes & Fixes

In this tutorial, we will discuss what a Java ArrayIndexOutOfBoundsException is, what causes it and how to make sure that you avoid it.

What is an ArrayIndexOutOfBoundsException

An array-index out of bounds exception is a Java exception thrown due to the fact that the program is trying to access an element at a position that is outside an array’s limits or boundaries, hence the words “Out of bounds”. In other words, the program is trying to access an element at an index that is outside the array bounds. To understand array bounds, let us consider the following diagram

The picture above contains an array that consists of 7 elements. Each element in the array has its own index/position. In Java and many other programming languages, an index always starts with 0 and ends with the number of elements in the array -1. For example, the array above consists of 7 elements, therefore it’s indices start from 0 and end with 6 (7-1).

Attempting o access an element with an index less than 0 or more than 6 will cause Java to throw an ArrayIndexOutOfBoundsException. Now that we know the causes of an out of bounds exception, let us discuss some common mistakes that people fall into that cause the exception.

Accessing elements within a loop with the loop counter as the index

An operation that is often performed in programming is accessing a section of, or the entire array, within a loop. While doing so, one must take precautions as not to go out of the bounds of the array. For example, when using a loop counter as an index, a common mistake is to define the bounds from the counter with a value of 0 to the counter <= the length of array, as in the following example.

public class OutOfBoundsExample1 {

      public static void main(String[]args){

          int [] array = {4,8,15,16,23,42};

          System.out.println("The lottery numbers are ...");
          for(int i = 0; i<=array.length; i;++){ // here, i<=array.length will be true,even when i is equal to 6
                                                    //which will cause an ArrayIndexOutOfBoundsException

              System.out.println(".."+array[i]);

          }
      }
  }


Running the program will yield the following output.

The lottery numbers are ...
..4
..8
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
..15
..16
..23
..42
	at OutOfBoundsExample1.main(OutOfBoundsExample1.java:12)
Java Result: 1


We received the above output because of the loop condition "i <= array.length". First of all, array.length represents the number of elements in the array and not the last index value in the array. Since the array has six elements, it's index bounds are from 0 to 5. However, the loop condition will stay true even when the counter i is equal to 6. This is because array.length is 6. Therefore, make sure when looping over elements to know the range of your counter. The following piece of code is a fix to the previous one.

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


You can also use a foreach loop, which will eliminate the need of an index or a counter. This can also make your code more readable, specially when writing nested loops. We can convert the code above into a foreach loop as follows.

        for(int item: array){
            System.out.println(".."+item);
        }


Accessing 2D/multi-dimension array elements

Another common mistake new and beginner programmers make is to use the wrong index when accessing 2D and multi-dimension array elements. Take for example the following piece of code.

public class OutOfBoundsExample2{

      public static void main(String[]args){

          int [][] array2D = {
              {1,2,3,4},
              {5,6,7,8},
              {9,10,11,12}
                               };

          System.out.println("The 1st number, 1st row = "+array2D[0][0]);
          System.out.println("The 2nd number, 1st row = "+array2D[1][0]);
          System.out.println("The 3rd number, 1st row = "+array2D[2][0]);
          System.out.println("The 4th number, 1st row = "+array2D[3][0]); //Beeeeeeeep! Out of bounds Exception

      }
  }


The above code will cause an ArrayIndexOutOfBoundsException to be thrown at the fourth print statement. This is because the statements tried to access the wrong array/row. The 2D array array2D consists of 3 rows and 4 columns. Therefore, in order to access a certain element within the array, we would first have to access the row, and then the column.

Since a 2D array is an array of arrays, we can consider each row as an individual array. To access a row, we use "array2D[row]". To access an element within a row, we use an index within that row, hence we use the statement "array2D[row][column]". Obviously, the program above has flipped the indices and will cause an exception to be thrown.

The 1st number, 1st row = 1
The 2nd number, 1st row = 5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
The 3rd number, 1st row = 9
	at OutOfBoundsExample1.main(OutOfBoundsExample1.java:15)
Java Result: 1


To fix the program above, we simply have to flip the indices as follows.

          System.out.println;("The 1st number, 1st row = "+array2D[0][0]);
          System.out.println;("The 2nd number, 1st row = "+array2D[0][1]);
          System.out.println;("The 3rd number, 1st row = "+array2D[0][2]);
          System.out.println;("The 4th number, 1st row = "+array2D[0][3]);



Summary

In this tutorial, we discussed some common mistakes that take place when dealing with arrays and why we could get an ArrayOutOfBoundsException.

If you liked this content, then please subscribe to our newsletter and make sure to follow us on twitter to be up to date with the latest posts and Java tutorials.