Sub topic 3
Handling null with `case null`
This chapter assumes you know Java classes, interfaces, inheritance, instanceof, casting, and switch expressions. You also need JDK 21 or newer.
A type pattern matches a non-null object of a given type. For example, case String s matches a String and binds it to s. It does not match null. Java treats null separately, so use the case null label when a switch should handle it explicitly.
Why `null` needs its own case
Without case null, a pattern switch throws NullPointerException when its selector is null. The selector is the value placed after switch.
This behavior is deliberate. A type pattern cannot bind a useful object variable when there is no object. A String pattern therefore cannot act as a null check.
public class NullSwitchDemo {
static String describe(Object value) {
return switch (value) {
case null -> "no value";
case String s -> "text: " + s;
case Integer i -> "number: " + i;
default -> "other value";
};
}
public static void main(String[] args) {
System.out.println(describe(null));
System.out.println(describe("hello"));
System.out.println(describe(42));
System.out.println(describe(true));
}
}The output is:
no value
text: hello
number: 42
other valueThe case null label must appear as its own label. It does not declare a variable because there is no object to bind.
A default label still handles non-null values that do not match an earlier pattern. It does not replace case null when you want a clear, intentional null result.
The matching order
Java checks the cases from top to bottom. For a switch with case null, the process is:
Put case null before ordinary type cases when reading order matters. It is also common to put it first because null is a special input and deserves immediate attention.
For a sealed hierarchy, cases for every permitted subtype can make a switch exhaustive for non-null values. Null is still separate. If the switch should accept null, include case null:
sealed interface Result permits Success, Failure {}
record Success(String message) implements Result {}
record Failure(String reason) implements Result {}
static String display(Result result) {
return switch (result) {
case null -> "missing result";
case Success s -> "success: " + s.message();
case Failure f -> "failure: " + f.reason();
};
}If case null is removed, the subtype cases may still cover every permitted non-null Result, but passing null causes NullPointerException.
case null is useful when null has a defined meaning, such as “not supplied” or “no result.” If null indicates a programming error, letting the switch throw can expose that error sooner. Choose the behavior at the boundary where the value is interpreted.
Exercise
What happens when describe(null) is called in the first example, and which case handles the value?
Show answer
It returns "no value". The case null label handles the null selector before Java tests the type patterns.