J.IV · Java 25 practice question
What happens when the following Java 25 program is compiled and run?
import java.util.List;
void main() {
List<String> items = List.of("alpha", null);
IO.println(items.size());
}
Check answer and explanation
Correct answer: It throws NullPointerException at runtime.
Explanation
List implementations that prohibit null elements throw an unchecked exception—typically NullPointerException—when an ineligible null element is supplied, and List.of prohibits nulls.
Common trap
ArrayList allows null elements and would have size 2, which makes this tempting if you forget that List.of prohibits nulls. The null prohibition is enforced at runtime by the factory method, not as a compile-time error.
Source: Java SE 25 API: List
Checked against the cited text on 2026-11-25.