Sub topic 3
Handling null with case null
This chapter assumes you know classic switch statements and switch expressions, the instanceof operator, and the type patterns from the previous two chapters. You need JDK 21 or newer to run the examples.
Why null needs a decision
Before Java 21, a switch on an enum, a String or a boxed type threw a NullPointerException (NPE) when the selector was null. Programmers either checked for null before the switch or accepted the exception.
Pattern switches keep that default and add an explicit way out. The rule has two parts:
- If the selector is
nulland the switch has nocase null, the switch throwsNullPointerException. - If the switch has a
case null, that case runs and nothing is thrown.
No other label matches null. This includes default and a type pattern that covers every value of the selector's type. Matching null is always opt-in.
public class NullDemo {
static String label(Object o) {
return switch (o) {
case String s -> "string " + s;
case Integer i -> "int " + i;
default -> "other";
};
}
public static void main(String[] args) {
System.out.println(label("hi"));
try {
label(null);
} catch (NullPointerException e) {
System.out.println("NullPointerException: default did not match null");
}
}
}The default branch looks like a catch-all, but it only catches non-null values. Java chose this to keep old code working. Every existing switch already threw an NPE on null, and they still do.
How a switch evaluates a null selector
The null check happens before any label is tested. Because of this, the position of case null among the other cases does not change the behavior. The usual style is to put it first, so a reader sees the null handling straight away.
Writing case null
Add case null as an ordinary branch. This is the example from the spine, with a full class around it.
public class NullCase {
static String describe(Object o) {
return switch (o) {
case null -> "null";
case Integer i when i > 100 -> "large int " + i;
case Integer i -> "int " + i;
case String s when s.isBlank() -> "blank string";
case String s -> "string of length " + s.length();
default -> "other: " + o;
};
}
public static void main(String[] args) {
System.out.println(describe(null));
System.out.println(describe(250));
System.out.println(describe(" "));
System.out.println(describe("hello"));
System.out.println(describe(3.5));
}
}The output is null, large int 250, blank string, string of length 5 and other: 3.5.
Inside the case null branch you have no variable to use. The only thing you know is that the value is null.
Sharing a branch with default
If null and "everything else" should behave the same way, combine the labels with case null, default.
static String safeName(Object o) {
return switch (o) {
case String s -> "name " + s;
case Integer i -> "id " + i;
case null, default -> "unknown";
};
}case null, default is the only way to put null in a multi-label case with another label. Because default matches everything, this label must come after all the pattern labels. A default that sits before a pattern label is a compile-time error, because it would make the later patterns unreachable.
Rules for the case null label
| Form | Allowed | Notes |
|---|---|---|
| `case null ->` | Yes | A branch of its own |
| `case null, default ->` | Yes | Handles `null` and any value no other label matched |
| `case null, String s ->` | No | A pattern that binds a variable cannot share a case with `null`, because `s` would have no value |
| `case null, "a" ->` | No | `null` can only be paired with `default` |
| Two `case null` labels in one switch | No | Duplicate label |
Here is the kind of code that fails to compile:
static String broken(Object o) {
return switch (o) {
case null, String s -> "text or null"; // does not compile
default -> "other";
};
}If you need both behaviors, write two branches. The method body can be shared by calling a helper from each.
Old-style switches accept case null too
case null is not limited to pattern switches. Since Java 21 it also works in switches over enums, strings and boxed types, with either arrow or colon syntax.
public class EnumNull {
enum Level { LOW, HIGH }
static String rate(Level level) {
return switch (level) {
case null -> "unknown";
case LOW -> "low";
case HIGH -> "high";
};
}
public static void main(String[] args) {
System.out.println(rate(Level.HIGH));
System.out.println(rate(null));
}
}This switch is exhaustive and null-safe. Without the case null line it would still compile and be exhaustive. It would then throw an NPE for rate(null).
Null and exhaustiveness
An exhaustive switch expression over a sealed type does not need case null. Exhaustiveness covers all non-null values of the type. A null selector still throws, as it would anywhere else.
sealed interface Shape permits Circle, Square {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square s -> s.side() * s.side();
};
}Calling area(null) throws NullPointerException. This is often what you want. A null shape is a bug in the caller, and failing fast shows it. Add case null only when null is a legitimate input with a meaningful result.
Null inside record patterns
Two different rules apply here, and mixing them up causes bugs.
- A record pattern never matches a
nullrecord.case Circle(var r)does not match anullselector, andcase nullis how you handle that. - A nested pattern can match a
nullcomponent, but only when it is an unconditional pattern for the component's type. A pattern is unconditional when it matches every value of that type. Avarpattern always is. So is a type pattern whose type is the component's own type or a supertype of it.
public class NullComponent {
record Box<T>(T content) {}
static String peek(Box<Object> box) {
return switch (box) {
case null -> "no box";
case Box<Object>(String s) -> "string of length " + s.length();
case Box<Object>(var o) -> "other content: " + o;
};
}
public static void main(String[] args) {
System.out.println(peek(null));
System.out.println(peek(new Box<>("abc")));
System.out.println(peek(new Box<>(null)));
}
}The output is no box, string of length 3 and other content: null.
Box<Object>(String s) is not unconditional, because Object is wider than String. It tests the component's type, and null fails that test. The third case uses var o, which is unconditional, so it catches the null content and binds o to null.
Be careful with an unconditional nested pattern on a variable you then dereference. With Box<String>(var s) or Box<String>(String s), the variable s can be null, and calling s.length() throws an NPE.
Common errors
- Assuming
defaultcatchesnull. It does not. A switch withdefaultand nocase nullstill throws onnull. - Putting
case nullin a combined label. Onlycase null, defaultis legal. Anything else is a compile-time error. - Forgetting that
instanceofnever matchesnull.o instanceof String sisfalsefor anullo, soif (!(o instanceof String s))runs fornull. Anullvalue falls into the "not a String" branch. - Trusting an exhaustive switch to be null-safe. Exhaustiveness is about types, not about the
nullvalue. - Dereferencing a binding from an unconditional pattern. This is the record-component case above.
Deciding where to handle null
| Situation | Choice |
|---|---|
| `null` is a bug in the caller | Leave out `case null` and let the NPE surface, or call `Objects.requireNonNull` for a clearer message |
| `null` has its own meaning, such as "no value" | Use a dedicated `case null` branch |
| `null` and unrecognized values get the same result | Use `case null, default` |
| You only need a null check before one test | An `if` with `instanceof` is often simpler than a switch |
Exercise
What does this method return for f(null), and what does it return for f("x")?
static String f(Object o) {
return switch (o) {
case String s -> "string";
case Object x -> "object";
};
}
Show answer
f(null) throws a NullPointerException. The pattern case Object x is unconditional, but a pattern label does not match null unless the switch has a case null. f("x") returns "string".
Exercise
A switch over a sealed Shape has case Circle c and case Square s. You want null to produce the text "no shape" and every shape to behave as before. What do you add, and does the switch still need a default?
Show answer
Add case null -> "no shape" as another branch. The switch still does not need a default, because the two shape cases already cover every non-null Shape and case null covers the null value.