Java – Find the Array Index of an element
This post shows you an easy way how to find the index of an element in an array in Java.
Here is the code:
ArrayExample.java
package com.bytenota;
import java.util.Arrays;
public class ArrayExample {
public static void main(String[] args) {
Integer[] array = { 10, 20, 30, 40, 50, 60, 70, 80 };
// find the index of 30 in array
int index = Arrays.asList(array).indexOf(30);
// print the result index out
System.out.println("index of 30 is " + index);
}
}
In the above code, we convert the array to List
using Arrays.asList()
method, then use indexOf()
to find the index of the given element (i.e. 30).
Output:
index of 30 is 2