Saturday, November 22, 2025
HomeLanguagesJavaJava Program to Check Whether an Element Occurs in a List

Java Program to Check Whether an Element Occurs in a List

The List Interface in Java represents an ordered collection or sequence. This Interface helps us control where to insert elements and also access elements through an integer index. This Interface is a member of the Java Collections Framework and the java.util package. The classes that implement the List Interface include ArrayList, LinkedList, Stack, and Vector. The Vector class has been deprecated since Java 5.

The classes, ArrayList, LinkedList, and Stack, all use the contains() method to check whether an element occurs in the List.

The contains() method of List interface in Java is used for checking if the specified element exists in the given list or not.

Syntax:

public boolean contains(Object obj)

object-element to be searched for

Parameters: This method accepts a single parameter obj whose presence in this list is to be tested.

Return Value: It returns true if the specified element is found in the list else it returns false.

Steps:

  1. Import the necessary packages. In this case, we need to import the java.util package.
  2. Create an ArrayList with the help of the List Interface.
  3. Add elements to the ArrayList using the add() method.
  4. Check whether the required element occurs in the ArrayList with the help of the contains() method.

Example:

Java




// Java program to check whether an element
// is present in an ArrayList
  
// importing package
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        // Creating an ArrayList of String type
        List<String> GFG = new ArrayList<String>();
  
        // Adding elements to the ArrayList
        GFG.add("Welcome");
        GFG.add("To");
        GFG.add("Geeks");
        GFG.add("For");
        GFG.add("Geeks");
  
        //  Using contains() method to check whether the
        //  particular
        // element is present in the List or not
        System.out.println(GFG.contains("Welcome")); 
        System.out.println(GFG.contains("Java")); 
    }
}


Output

true
false
RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6864 POSTS0 COMMENTS
Umr Jansen
6852 POSTS0 COMMENTS