Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
arrayutils
communitycreator

What is ArrayUtils.indexOf in Java?

abhilash

indexof is a static method of the ArrayUtils class that finds the index of a given element in the given array from the starting index.

  • A negative start index will be converted to zero.

  • -1 will be returned if the start index is larger than the length of the array.

  • -1 will be returned if the value cannot be found in the array.

Example 1

  • Array = [1,2,3,4,5]
  • Element = 5
  • Start index = 2

4 is the result of the application of the indexOf function because the element 5 is found at index 4, which begins at index 2.

Example 2

  • Array = [1,2,3,4,5]
  • Element = 100
  • Start index = 0

-1 is the result of the application of the indexOf function because the element 100 is not found in the array, which starts at the index 0.

Example 3

  • Array = [1,2,3,4,5]
  • Element = 3
  • Start index = 100

-1 is the result of the application of the indexOf function because the start index is greater than the length of the array.

ArrayUtils is defined in the To add Apache Commons Lang package. Apache Commons Lang to the Maven Project, add 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 int indexOf(final int[] array, final int valueToFind, int startIndex)

Parameters

  • final int[] array : array of elements.
  • final int valueToFind : the element to be searched.
  • final startIndex : the start index from where the search begins.

Return value

This function returns the index of the value at the given index, if it is found in the array. Otherwise, -1 is returned for the values not found in the array.

Code

import org.apache.commons.lang3.ArrayUtils;

public class Main {

    public static void main(String[] args) {
        int[] array = {1,2,3,4,5};
        System.out.println(ArrayUtils.indexOf(array, 5, 2));
        System.out.println(ArrayUtils.indexOf(array, 100, 0));
        System.out.println(ArrayUtils.indexOf(array, 3, 100));
    }
}

Expected output

4
-1
-1

RELATED TAGS

java
arrayutils
communitycreator
RELATED COURSES

View all Courses

Keep Exploring