Skip to content
Advertisement

How to use null in switch

Integer i = ...
    
switch (i) {
    case null:
        doSomething0();
        break;    
}

In the code above I can’t use null in the switch case statement. How can I do this differently? I can’t use default because then I want to do something else.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement