Collections: List.of is immutable and rejects nulls

The Java 9 factory methods return space-efficient immutable lists. They throw on modification and on null elements, which catches bugs early.

Code
var fixed = List.of("a", "b", "c");
System.out.println(fixed);

try {
    fixed.add("d");
} catch (UnsupportedOperationException e) {
    System.out.println("List.of cannot be modified");
}
try {
    List.of("a", null);
} catch (NullPointerException e) {
    System.out.println("List.of rejects null elements");
}
System.out.println("Arrays.asList allows null: " + Arrays.asList("a", null));
Output
[a, b, c]
List.of cannot be modified
List.of rejects null elements
Arrays.asList allows null: [a, null]
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30