Java MCQ: What is the purpose of the Java 9 List.of() method?
Answer:
Explanation:
The List.of()
method introduced in Java 9 is used to create an immutable List. An immutable list is a list that cannot be modified after it is created, meaning that no elements can be added, removed, or changed.
Here’s an example of using List.of()
:
import java.util.List;
public class ListOfExample {
public static void main(String[] args) {
List<String> names = List.of("John", "Jane", "Jack");
System.out.println(names);
// This will throw UnsupportedOperationException because the list is immutable
// names.add("Doe");
}
}
In this example, List.of("John", "Jane", "Jack")
creates an immutable list containing three elements. Any attempt to modify the list (e.g., adding or removing elements) will result in an UnsupportedOperationException
.
List.of()
is particularly useful for creating small, fixed collections of elements where immutability is desired, ensuring that the list remains constant throughout its lifetime.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html