Saturday, September 6, 2025
HomeLanguagesJavaJava Collections emptySet() Method with Examples

Java Collections emptySet() Method with Examples

The emptySet() method is used to get the set that has no elements. This method is used in set collection. A set is a data structure that can store unique elements.

Syntax:

public static final <T> Set<T> emptySet()   

Parameters: This method will take no parameters.

Return Type: It will return an empty set that is immutable.

Example 1:

Java program to create an empty set

Java




import java.util.*;
  
public class GFG {
    // main method
    public static void main(String[] args)
    {
        // create an empty set
        Set<String> data = Collections.<String>emptySet();
        
        // display
        System.out.println(data);
    }
}


Output

[]

Example 2:

In this program, we are going to create an empty set and add elements to the set. This method will return an error.

Java




import java.util.*;
  
public class GFG {
    // main method
    public static void main(String[] args)
    {
        // create an empty set
        Set<String> data = Collections.<String>emptySet();
        
        // add 3 elements
        data.add("ojaswi");
        data.add("ramya");
        data.add("deepu");
  
        // display
        System.out.println(data);
    }
}


Output:

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractCollection.add(AbstractCollection.java:262)
    at GFG.main(GFG.java:8)
RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS