Java Set contains() example

In this guide, you will learn about the Set contains() method in Java programming and how to use it with an example.

1. Set contains() Method Overview


The contains() method of the Java Set interface returns true if the set contains the specified element.


boolean exists = set.contains(Object o);


- Object o: The element whose presence in this set is to be tested.

Key Points:

- The method returns true if this set contains the specified element.

- This method uses the equals method of the elements to check for equality.

- If the set contains the specified element, it returns true, otherwise, it returns false.

- The method throws a ClassCastException if the type of the specified element is incompatible with this set (optional).

- It also throws a NullPointerException if the specified element is null and this set does not support null elements (optional).

2. Set contains() Method Example

import java.util.HashSet;
import java.util.Set;

public class SetContainsExample {
    public static void main(String[] args) {
        Set<String> fruits = new HashSet<>();

        // Adding elements to the set

        // Checking if set contains specific elements
        System.out.println("Does the set contain 'Apple'? : " + fruits.contains("Apple"));  // true
        System.out.println("Does the set contain 'Grape'? : " + fruits.contains("Grape"));  // false

        // Using contains() with a null value
        fruits.add(null);  // Assuming the set implementation allows null
        System.out.println("Does the set contain null? : " + fruits.contains(null));  // true


Does the set contain 'Apple'? : true
Does the set contain 'Grape'? : false
Does the set contain null? : true


In this example:

1. We create a HashSet of fruits.

2. We add three fruits: "Apple", "Banana", and "Cherry" to the set.

3. We then check for the presence of "Apple" and "Grape" using the contains() method. As expected, "Apple" exists, while "Grape" does not.

4. We then demonstrate how the contains() method works with null values (assuming the set implementation supports null values).

The contains() method is essential to determine the presence of an element in a set without having to traverse the entire set manually.

Related Java Set interface methods

Java Set add() example
Java Set contains() example
Java Set isEmpty() example
Java Set remove() example
Java Set size() example