Blog |

How to Fix the Array Index Out Of Bounds Exception in Java

How to Fix the Array Index Out Of Bounds Exception in Java
Table of Contents

The ArrayIndexOutOfBoundsException is a runtime exception in Java that occurs when an array is accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Let’s put that in simpler terms with an analogy. Imagine you have a row of five boxes lined up in front of you. Each box has a number on it. If you want to put a toy in one of these boxes, you have to say which box number you're putting it in. For example, "Put this toy in box number 2."

But what if you say, "Put this toy in box number 6"? There's no box number 6 because you only have five boxes. So, it's like asking for something that doesn't exist, and that causes a problem. Think of ArrayIndexOutOfBoundsException then as Java's way of saying, "Hey, that box number doesn't exist!"

What Causes ArrayIndexOutOfBoundsException

The ArrayIndexOutOfBoundsException is one of the most common errors in Java.

Since a Java array has a range of [0, array length - 1], when an attempt is made to access an index outside this range, an ArrayIndexOutOfBoundsException is thrown.

Besides arrays, this exception can also happen with strings, ArrayLists, and any other data structure that uses indexing to access elements.

ArrayIndexOutOfBoundsException Example

Here is an example of a ArrayIndexOutOfBoundsException thrown when an attempt is made to retrieve an element at an index that falls outside the range of the array:

public class ArrayIndexOutOfBoundsExceptionExample {
    public static void main(String[] args) {
        String[] arr = new String[10]; 
        System.out.println(arr[10]); // Attempt to access an element at index 10, which does not exist
    }
}

In this example, a String array of length 10 is created. An attempt is then made to access an element at index 10, which falls just outside the 0-9 range of the array, throwing an ArrayIndexOutOfBoundsException:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
    at ArrayIndexOutOfBoundsExceptionExample.main(ArrayIndexOutOfBoundsExceptionExample.java:4)

 

How to Fix ArrayIndexOutOfBoundsException

To avoid the ArrayIndexOutOfBoundsException, the following should be kept in mind:

  • The bounds of an array should be checked before accessing its elements.
  • An array in Java starts at index 0 and ends at index length - 1, so accessing elements that fall outside this range will throw an ArrayIndexOutOfBoundsException.
  • An empty array has no elements, so attempting to access an element will throw the exception.
  • When using loops to iterate over the elements of an array, attention should be paid to the start and end conditions of the loop to make sure they fall within the bounds of an array. An enhanced for loop can also be used to ensure this.

Since the ArrayIndexOutOfBoundsException is an unchecked exception, it doesn’t need to be declared in the throws clause of a method or constructor. That said, there’s no reason you couldn’t still use a try-catch blog to handle the exception and print a friendly error message, preventing the program from crashing. Like this for example:


public class ArrayIndexOutOfBoundsExceptionExample {
    public static void main(String[] args) {
        String[] arr = new String[10];
        try {
            System.out.println(arr[10]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Caught an ArrayIndexOutOfBoundsException: " + e.getMessage());
        }
    }
}

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape