What is the behavior of the Map.copyOf() method introduced in Java 10 when invoked with a map containing null keys or values?

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?

a) It removes the null keys or values from the map
b) It replaces null keys or values with empty strings
c) It throws a NullPointerException
d) It converts null keys or values to zeros

Answer:

c) It throws a NullPointerException

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

Leave a Comment

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

Scroll to Top