How to use null in switch
switch(i)
will throw a NullPointerException if i is null
, because it will try to unbox the Integer
into an int
. So case null
, which happens to be illegal, would never have been reached anyway.
You need to check that i is not null before the switch
statement.
This is was not possible with a switch
statement in Java until Java 18. You had to check for null
before the switch
. But now, with pattern matching, this is a thing of the past. Have a look at JEP 420:
Pattern matching and null
Traditionally, switch statements and expressions throw NullPointerException if the selector expression evaluates to null, so testing for null must be done outside of the switch:
static void testFooBar(String s) {
if (s == null) {
System.out.println("oops!");
return;
}
switch (s) {
case "Foo", "Bar" -> System.out.println("Great");
default -> System.out.println("Ok");
}
}
This was reasonable when switch supported only a few reference types. However, if switch allows a selector expression of any type, and case labels can have type patterns, then the standalone null test feels like an arbitrary distinction, and invites needless boilerplate and opportunity for error. It would be better to integrate the null test into the switch:
static void testFooBar(String s) {
switch (s) {
case null -> System.out.println("Oops");
case "Foo", "Bar" -> System.out.println("Great");
default -> System.out.println("Ok");
}
}
More about switch
(including example with null variable) in Oracle Docs - Switch
switch ((i != null) ? i : DEFAULT_VALUE) {
//...
}