Find Index of Element in Java Array

You can find the index of an element in an array in many ways like using a looping statement and finding a match, or by using ArrayUtils from commons library.

In this tutorial, we will go through each of these process and provide example for each one of them for finding index of an element in an array.

Find Index of Element in Array using Looping Technique

Using While Loop

In the following example, we will use while loop to find the index of first occurrence of a given element in array. We shall use while loop to traverse the array elements, and when we find a match, we have the required index.

Java Program

public class ArrayExample {
	public static void main(String[] args) {
		int[] numbers = {4, 9, 7, 3, 2, 8}; 
		int element = 2;
		int index = -1;
		
		int i = 0;
		while(i < numbers.length) {
			if(numbers[i] == element) {
				index = i;
				break;
			}
			i++;
		}
		
		System.out.println("Index of "+element+" is : "+index);
	}
}

Output

Index of 2 is : 4

If the given element is present in the array, we get an index that is non negative. If the given element is not present, the index will have a value of -1.

Using For Loop

In the following example, we will use for loop to find the index of a given element in array.

Java Program

public class ArrayExample {
	public static void main(String[] args) {
		int[] numbers = {4, 9, 7, 3, 2, 8}; 
		int element = 2;
		int index = -1;
		
		for(int i = 0; i < numbers.length; i++) {
			if(numbers[i] == element) {
				index = i;
				break;
			}
		}
		
		System.out.println("Index of "+element+" is : "+index);
	}
}

Output

Index of 2 is : 4

If the given element is present in the array, we get an index that is non negative. If the given element is not present, the index will have a value of -1.

ADVERTISEMENT

Find Index of Element in Array using Looping ArrayUtils

ArrayUtils.indexOf(array, element) method finds the index of element in array and returns the index.

Java Program

import org.apache.commons.lang.ArrayUtils;

public class ArrayExample {
	public static void main(String[] args) {
		int[] numbers = {4, 9, 7, 3, 2, 8}; 
		int element = 2;
		
		int index = ArrayUtils.indexOf(numbers, element);
		
		System.out.println("Index of "+element+" is : "+index);
	}
}

Output

Index of 2 is : 4

Conclusion

In this Java Tutorial, we learned how to find the index of an given element in the array, with the help of example Java programs.