Java MCQ: What happens if you use the Java 9 List.of() method with null elements?
Answer:
Explanation:
Using the List.of()
method introduced in Java 9 with null elements will result in a NullPointerException
. The List.of()
method is designed to create an immutable list, and one of the constraints is that it does not allow null elements. Attempting to create a list with null elements using List.of()
will immediately throw a NullPointerException
.
Here’s an example that demonstrates this behavior:
import java.util.List;
public class ListOfNullExample {
public static void main(String[] args) {
// This will throw NullPointerException because the list contains null
List<String> list = List.of("John", null, "Jane");
}
}
In this example, the List.of("John", null, "Jane")
statement will throw a NullPointerException
because the list contains a null element. This strict enforcement of non-null elements ensures the immutability and consistency of the list created with List.of()
.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html