What are Index and Array Out of Bounds Exception

Overview

1. Introduction

In this article, we'll visit what ArrayIndexOutOfBoundsException and IndexOutOfBoundsException are and how they occur when working with arrays and lists.

2. What is an ArrayIndexOutOfBoundsException

To understand that exception, we need first to introduce what an array is. Here's one possible definition for an array in Java:

A linear structure where each element is associated with an index from 0 to N, where N is the array size.

If we try to access a place in memory not associated with the defined array, JDK returns an ArrayIndexOutOfBoundsException. To illustrate that scenario, let's take a look at the following example:

1  public static void main(String[] args) {
2    int[] primitiveArray = new int[]{2, 1, 4, -1};
3    int number = primitiveArray[4]; // -> throws java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
4  }

In the above code, the primitiveArray variable is represented as follows in memory:

0 1 2 3
2 1 4 -1

Important note: Any array or list in Java has its indexes starting from 0.

The illustration of memory shows that index 4 doesn't exist for primitiveArray. That position belongs to anything else not related to that variable. Thus, when we try to capture the element at index 4, we'll get an _ArrayIndexOutOfBoundsException_because we're trying to access something outside the array memory boundaries.

3. What is the IndexOutOfBoundsException

Behind the scenes, any implementation of List in Java uses an array to store its elements, just like primitiveArray in the previous example. Thus, the same error with a different name might also happen to lists. Let's try another example:

1  public static void main(String[] args) {
2    List<Integer> list = new ArrayList<>(Arrays.asList(2, 1, 4, -1)); // -> creates a list with elements [2, 1, 4, -1]
3    int number = list.get(4); // -> throws java.lang.IndexOutOfBoundsException: Index 4 out of bounds for length 4
4  }

The list variable is represented as follows in memory:

0 1 2 3
2 1 4 -1

As index 4 is not part of the list variable, JDK also throws an exception in this case.

Notice that the exception changed its type to IndexOutOfBoundsException, but it means the same thing. We're trying to access a position outside of the list boundaries. The only difference is that ArrayIndexOutOfBoundsException is thrown by arrays, while IndexOutOfBoundsException is by any implementation of List.

4. Problems in for Loops

It is a common scenario when using for loops to encounter either ArrayIndexOutOfBoundsException and IndexOutOfBoundsException. Let's have a look at one example:

1  public static void main(String[] args) {
2    int[] primitiveArray = new int[]{2, 1, 4, -1};
3
4    for (int i = 0; i <= primitiveArray.length; i++) {
5      System.out.println(primitiveArray[i]); // -> java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
6    }
7  }

Notice that the for loop starts from i = 0 and increases to the array's size equal to 4. Thus, when i = 4, the exception is thrown. If we run this code, we'll get the following output:

12
21
34
4-1
5Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4

The for loop normally runs when i equals 0 to 3. However, JDK throws the exception when the loop tries to access index 4.

4.2. How to Avoid Exceptions in for Loops

One way, probably the simplest, to avoid IndexOutOfBoundsException and ArrayIndexOutOfBoundsException in for loops is using the enhanced for loops, which uses an iterator. Let's see one example of the enhanced for loop:

 1  public static void main(String[] args) {
 2    int[] primitiveArray = new int[]{2, 1, 4, -1};
 3    List<Integer> list = new ArrayList<>(Arrays.asList(2, 1, 4, -1));
 4
 5    for (int number : primitiveArray) { // -> iterator version of for loop in arrays
 6      System.out.println(number); // -> No errors.
 7    }
 8
 9    for (int number : list) {  // -> iterator version of for loop in Lists
10      System.out.println(number); // -> No errors.
11    }
12  }

Using enhanced for with an iterator, we don't need to access indexes directly. The iterator does that for us behind the scenes. That makes the code less prone to any out-of-bounds exception.

5. Conclusion

In this article, we've seen one way to avoid the ArrayIndexOutOfBoundsException and IndexOutOfBoundsException using the enhanced for loops version with an iterator.