# Get the location of an element in Java ArrayList

Java 8Object Oriented ProgrammingProgramming

The location of an element in an ArrayList can be obtained using the method java.util.ArrayList.indexOf(). This method returns the index of the first occurrence of the element that is specified. If the element is not available in the ArrayList, then this method returns -1.

A program that demonstrates this is given as follows −

## Example

Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
List aList = new ArrayList();
System.out.println("The index of element C in ArrayList is: " + aList.indexOf("C"));
System.out.println("The index of element F in ArrayList is: " + aList.indexOf("F"));
}
}

## Output

The index of element C in ArrayList is: 2
The index of element F in ArrayList is: -1

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.indexOf() returns the index of the first occurrence of “C” and “F” that is displayed. A code snippet which demonstrates this is as follows −

List aList = new ArrayList();
System.out.println("The index of element F in ArrayList is: " + aList.indexOf("F"));