Which of the following best describes the purpose of the Set.of() method in Java 9?

Java MCQ: Which of the following best describes the purpose of the Set.of() method in Java 9?

a) To create a mutable set
b) To create an immutable set
c) To create a set with duplicate elements
d) To convert a list to a set

Answer:

b) To create an immutable set

Explanation:

The Set.of() method introduced in Java 9 is used to create an immutable set. An immutable set is a set that cannot be modified after it is created, meaning that no elements can be added, removed, or changed. Any attempt to modify the set will result in an UnsupportedOperationException.

Here’s an example of using Set.of():

import java.util.Set;

public class SetOfExample {
    public static void main(String[] args) {
        Set<String> fruits = Set.of("Apple", "Banana", "Cherry");
        System.out.println(fruits);

        // This will throw UnsupportedOperationException because the set is immutable
        // fruits.add("Mango");
    }
}

In this example, Set.of("Apple", "Banana", "Cherry") creates an immutable set containing three elements. Any attempt to modify the set (e.g., adding or removing elements) will result in an UnsupportedOperationException.

Set.of() is useful for creating small, fixed sets of elements where immutability is desired, ensuring that the set remains constant and unmodifiable throughout its lifetime.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top