Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
array
communitycreator

What is ArrayUtils.isArrayIndexValid in Java?

abhilash

isArrayIndexValid is a static method of the ArrayUtils class that states whether a given index is within the bounds of the array, i.e., the index should be greater than or equal to zero and less than the length of the array.

0 <= index < array_length

Arrays in Java follow zero-based indexing.

Example 1

  • array = [1,2,3,4,5]
  • index = 2

Applying the isArrayIndexValid function will result in true, as the index is within the bounds.

Example 2

  • array = [1,2,3,4,5]
  • index = 10

Applying the isArrayIndexValid function will result in false, as the index is out of bounds.

ArrayUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml file.

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

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the ArrayUtils class as follows:

import org.apache.commons.lang3.ArrayUtils;

Syntax

public static <T> boolean isArrayIndexValid(final T[] array, final int index)

Parameters

  • final T[] array: An array of elements.
  • final int index: Index to check.

Type parameters

  • <T>: The data type of the array.

Returns

This method returns true if the index can be safely accessed in the given array, and returns false otherwise.

Code

import org.apache.commons.lang3.ArrayUtils;

public class Main {

    public static void main(String[] args) {
        Integer[] array = {1,2,3,4,5,2,3,2,2,4};
        boolean check = ArrayUtils.isArrayIndexValid(array, 3);
        System.out.println("Index 3 is accessible in the array - " + check);
        check = ArrayUtils.isArrayIndexValid(array, 100);
        System.out.println("Index 100 is accessible in the array - " + check);
    }
}

Expected output

Index 3 is accessible in the array - true
Index 100 is accessible in the array - false

RELATED TAGS

java
array
communitycreator
RELATED COURSES

View all Courses

Keep Exploring