Java MCQ: Which of the following best describes the purpose of the Set.of() method in Java 9?
Answer:
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