Java MCQ: What is the behavior of the Map.copyOf() method introduced in Java 10 when invoked with a map containing null keys or values?
Answer:
Explanation:
The Map.copyOf()
method, introduced in Java 10, throws a NullPointerException
when invoked with a map containing null keys or values. This method creates an unmodifiable copy of the specified map, but it requires that the map does not contain any null keys or values. If the map contains null elements, Map.copyOf()
will throw a NullPointerException
to indicate that the operation cannot be completed.
Here’s an example that demonstrates this behavior:
import java.util.Map;
public class MapCopyOfExample {
public static void main(String[] args) {
Map<String, Integer> originalMap = Map.of("John", 25, "Jane", null);
// This will throw NullPointerException because the map contains a null value
Map<String, Integer> copyMap = Map.copyOf(originalMap);
}
}
In this example, the call to Map.copyOf(originalMap)
will throw a NullPointerException
because originalMap
contains a null value. This behavior ensures that only fully non-null maps can be copied using Map.copyOf()
.
The Map.copyOf()
method is useful for creating unmodifiable views of existing maps, but developers must ensure that the input map contains no null elements.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html