How to use null in switch

JavaSwitch Statement

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

This is not possible with a switch statement in Java. Check for null before the switch:

if (i == null) {
    doSomething0();
} else {
    switch (i) {
    case 1:
        // ...
        break;
    }
}

You can't use arbitrary objects in switch statements*. The reason that the compiler doesn't complain about switch (i) where i is an Integer is because Java auto-unboxes the Integer to an int. As assylias already said, the unboxing will throw a NullPointerException when i is null.

* Since Java 7 you can use String in switch statements.

More about switch (including example with null variable) in Oracle Docs - Switch

Solution 2 - Java

switch ((i != null) ? i : DEFAULT_VALUE) {
        //...
}

Solution 3 - Java

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.

Solution 4 - Java

Java docs clearly stated that:

The prohibition against using null as a switch label prevents one from writing code that can never be executed. If the switch expression is of a reference type, such as a boxed primitive type or an enum, a run-time error will occur if the expression evaluates to null at run-time.

You must have to verify for null before Swithch statement execution.

if (i == null)

See The Switch Statement

case null: // will never be executed, therefore disallowed.

Solution 5 - Java

Given:

public enum PersonType {
    COOL_GUY(1),
    JERK(2);

    private final int typeId;
    private PersonType(int typeId) {
        this.typeId = typeId;
    }

    public final int getTypeId() {
        return typeId;
    }

    public static PersonType findByTypeId(int typeId) {
        for (PersonType type : values()) {
            if (type.typeId == typeId) {
                return type;
            }
        }
        return null;
    }
}

For me, this typically aligns with a look-up table in a database (for rarely-updated tables only).

However, when I try to use findByTypeId in a switch statement (from, most likely, user input)...

int userInput = 3;
PersonType personType = PersonType.findByTypeId(userInput);
switch(personType) {
case COOL_GUY:
    // Do things only a cool guy would do.
    break;
case JERK:
    // Push back. Don't enable him.
    break;
default:
    // I don't know or care what to do with this mess.
}

...as others have stated, this results in an NPE @ switch(personType) {. One work-around (i.e., "solution") I started implementing was to add an UNKNOWN(-1) type.

public enum PersonType {
    UNKNOWN(-1),
    COOL_GUY(1),
    JERK(2);
    ...
    public static PersonType findByTypeId(int id) {
        ...
        return UNKNOWN;
    }
}

Now, you don't have to do null-checking where it counts and you can choose to, or not to, handle UNKNOWN types. (NOTE: -1 is an unlikely identifier in a business scenario, but obviously choose something that makes sense for your use-case).

Solution 6 - Java

You have to make a

if (i == null) {
   doSomething0();
} else {
   switch (i) {
   }
}

Solution 7 - Java

Some libraries attempt to offer alternatives to the builtin java switch statement. Vavr is one of them, they generalize it to pattern matching.

Here is an example from their documentation:

String s = Match(i).of(
    Case($(1), "one"),
    Case($(2), "two"),
    Case($(), "?")
);

You can use any predicate, but they offer many of them out of the box, and $(null) is perfectly legal. I find this a more elegant solution than the alternatives, but this requires java8 and a dependency on the vavr library...

Solution 8 - Java

You can also use String.valueOf((Object) nullableString) like

switch (String.valueOf((Object) nullableString)) {
case "someCase"
    //...
    break;
...
case "null": // or default:
    //...
        break;
}

> See interesting SO Q/A: Why does String.valueOf(null) throw a NullPointerException

Solution 9 - Java

Based on @tetsuo answer, with java 8 :

Integer i = ...

switch (Optional.ofNullable(i).orElse(DEFAULT_VALUE)) {
    case DEFAULT_VALUE:
        doDefault();
        break;    
}

Solution 10 - Java

You can't. You can use primitives (int, char, short, byte) and String (Strings in java 7 only) in switch. primitives can't be null.
Check i in separate condition before switch.

Solution 11 - Java

switch (String.valueOf(value)){
    case "null":
    default: 
}

Solution 12 - Java

I just learned today that you dont have to put another layer of indentation/curly brackets just because of the if that is checking for null. You can do either of these:

if (i == null) {
    // ...
} else switch (i) {
    case 1:
        // ...
        break;
    default:
        // ...
}

or

if (i != null) switch (i) {
    case 1:
        // ...
        break;
    default:
        // ...
} else {
    // ...
}

Solution 13 - Java

Just consider how the SWITCH might work,

  • in case of primitives we know it can fail with NPE for auto-boxing
  • but for String or enum, it might be invoking equals method, which obviously needs a LHS value on which equals is being invoked. So, given no method can be invoked on a null, switch cant handle null.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhudiView Question on Stackoverflow
Solution 1 - JavaJesperView Answer on Stackoverflow
Solution 2 - JavatetsuoView Answer on Stackoverflow
Solution 3 - JavaassyliasView Answer on Stackoverflow
Solution 4 - JavaShehzadView Answer on Stackoverflow
Solution 5 - JavaBeezView Answer on Stackoverflow
Solution 6 - JavaKaiView Answer on Stackoverflow
Solution 7 - JavaEmmanuel TouzeryView Answer on Stackoverflow
Solution 8 - JavaoikonomopoView Answer on Stackoverflow
Solution 9 - JavaCalfaterView Answer on Stackoverflow
Solution 10 - JavaMikita BelahlazauView Answer on Stackoverflow
Solution 11 - Javal0v3View Answer on Stackoverflow
Solution 12 - JavaTankki3View Answer on Stackoverflow
Solution 13 - JavaPuneetView Answer on Stackoverflow