Java Check an Array Index is valid using Apache Commons Lang

Tags: ArrayUtils Apache Commons Apache Commons Lang array

In this Java tutorial we learn how to check if a given index value is valid or not to access a given array using ArrayUtils class of Apache Commons Lang library.

How to add Apache Commons Lang 3 library to your Java project

To use the Apache Commons Lang 3 library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'org.apache.commons:commons-lang3:3.12.0'

To use the Apache Commons Lang 3 library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.12.0</version>
</dependency>

To have more information about the Apache Commons Lang 3 library you can visit the library home page at commons.apache.org/proper/commons-lang/

How to check an Array Index Valid in Java

The Apache Commons Lang library provides the method ArrayUtils.isArrayIndexValid() to return whether a given array can safely be accessed at the given index value. You can learn how to use the ArrayUtils.isArrayIndexValid() method in the following code example.

CheckArrayIndexValid.java

import org.apache.commons.lang3.ArrayUtils;

public class CheckArrayIndexValid {
    public static void main(String... args) {
        Integer[] arrayToCheck = new Integer[] { 1, 2, 3, 4, 5 };
        int indexToCheck1 = -1;
        int indexToCheck2 = 2;
        int indexToCheck3 = 7;

        boolean result1 = ArrayUtils.isArrayIndexValid(arrayToCheck, indexToCheck1);
        boolean result2 = ArrayUtils.isArrayIndexValid(arrayToCheck, indexToCheck2);
        boolean result3 = ArrayUtils.isArrayIndexValid(arrayToCheck, indexToCheck3);

        System.out.println("Index " + indexToCheck1 + " check valid result: " + result1);
        System.out.println("Index " + indexToCheck2 + " check valid result: " + result2);
        System.out.println("Index " + indexToCheck3 + " check valid result: " + result3);
    }
}
The output is:
Index -1 check valid result: false
Index 2 check valid result: true
Index 7 check valid result: false

Happy Coding 😊