Java MCQ: How does the Set.copyOf() method introduced in Java 10 behave when given a null argument?
Answer:
Explanation:
The Set.copyOf()
method, introduced in Java 10, throws a NullPointerException
when given a null argument. This method creates an unmodifiable copy of the specified set, but it requires that the provided set is non-null. If a null set is passed to Set.copyOf()
, the method will throw a NullPointerException
to indicate that the operation cannot proceed.
Here’s an example that demonstrates this behavior:
import java.util.Set;
public class SetCopyOfExample {
public static void main(String[] args) {
Set<String> originalSet = null;
// This will throw NullPointerException because the argument is null
Set<String> copySet = Set.copyOf(originalSet);
}
}
In this example, the call to Set.copyOf(originalSet)
will throw a NullPointerException
because originalSet
is null. This behavior ensures that only valid, non-null sets can be copied using Set.copyOf()
.
The Set.copyOf()
method is useful for creating unmodifiable views of existing sets, but developers must ensure that the input set is non-null.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html