J.IV · Java 25 practice question
A developer calls contains(null) on a List implementation that prohibits null elements. According to the Java SE 25 List specification, what behavior is permitted?
Check answer and explanation
Correct answer: It may either throw an exception or simply return false, depending on the implementation.
Explanation
The List specification states that querying the presence of an ineligible element may either throw an exception or simply return false, as different implementations exhibit different behavior.
Common trap
Returning false seems intuitive because the element cannot be present, but the specification explicitly allows throwing an exception. Although List.of throws NullPointerException on contains(null), the List contract does not mandate throwing for all null-prohibiting implementations.
Source: Java SE 25 API: List
Checked against the cited text on 2026-11-25.