[Java] How to find the index of given element in an array?


I want to find the position of a given element in an array, how can I do that in Java?

1 Answer

3 years ago by

List has indexOf method, so we can convert Array to List and call indexOf method on it.
Following code shows how to do that.

import java.util.Arrays;

public class JavaArrays {
	public static void main(String[] args) {
		String[] colors = { "red", "green", "blue", "orange", "maroon" };
		System.out.println(Arrays.asList(colors).indexOf("blue"));
	}
}

Output:

2

You can try the code online here: https://onecompiler.com/java/3xmt6qqfv

3 years ago by Karthik Divi