This post will discuss how to check if an index exists in Java array.

The ArrayIndexOutOfBoundsException is thrown whenever we’re trying to access an array index that is either negative or greater than or equal to the size of the array. For instance, the following code tries to access an invalid array index and results in an ArrayIndexOutOfBoundsException.

Download  Run Code

Output:

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 5
    at Main.main(Main.java:7)

 
To avoid getting an ArrayIndexOutOfBoundsException, we can explicitly check if the array index is within the bounds of the array before accessing it.

1. Custom routine to check length

A simple solution is to write a custom routine to check if an array index is valid or not. An array index is valid if it is non-negative and less than the size of the array. The array’s length can be determined from the final instance variable length.

Download  Run Code

Output:

Index 6 out of bounds for length 5

2. Using try-catch block

The idea here is to try accessing the array within a try-catch block. Return false if the code throws ArrayIndexOutOfBoundsException, true otherwise. The array can be accessed using an indexing expression, enclosed by [ and ].

Here’s the complete code:

Download  Run Code

Output:

Index 6 out of bounds for length 5

3. Using Objects.checkIndex() method

Since Java 9, we can check if the index is within the bounds of the specified range using the Objects.checkIndex() method. It returns the index if it is within bounds of the range and throws IndexOutOfBoundsException if the index is out of bounds. It can be used as follows:

Download  Run Code

Output:

Index 6 out of bounds for length 5

That’s all about checking if an index exists in Java array.