How to use null in switch

This 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 an example with a null variable) in Oracle Docs – Switch

Leave a Comment