Java MCQ: Which method in Java 9 is used to create an immutable Map with a variable number of key-value pairs?
Answer:
Explanation:
The Map.of()
method introduced in Java 9 is used to create an immutable Map with a variable number of key-value pairs. This method allows you to easily create a map with a small number of entries without the need for complex initialization or external libraries. The map created by Map.of()
is immutable, meaning it cannot be modified after creation.
Here’s an example of using Map.of()
:
import java.util.Map;
public class MapOfExample {
public static void main(String[] args) {
Map<String, Integer> ages = Map.of("John", 25, "Jane", 30, "Jack", 22);
System.out.println(ages);
// This will throw UnsupportedOperationException because the map is immutable
// ages.put("Doe", 35);
}
}
In this example, Map.of("John", 25, "Jane", 30, "Jack", 22)
creates an immutable map with three key-value pairs. Any attempt to modify the map (e.g., adding or changing entries) will result in an UnsupportedOperationException
.
Map.of()
is useful for creating small, fixed maps where immutability is desired, ensuring that the map 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