How to use null in switch

前端 未结 12 980
南方客
南方客 2020-12-04 10:17
Integer i = ...

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

In the code above I cant use null in switch case state

相关标签:
12条回答
  • 2020-12-04 11:08

    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.
    
    0 讨论(0)
  • 2020-12-04 11:10

    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

    0 讨论(0)
  • 2020-12-04 11:14

    Based on @tetsuo answer, with java 8 :

    Integer i = ...
    
    switch (Optional.ofNullable(i).orElse(DEFAULT_VALUE)) {
        case DEFAULT_VALUE:
            doDefault();
            break;    
    }
    
    0 讨论(0)
  • 2020-12-04 11:17
    switch ((i != null) ? i : DEFAULT_VALUE) {
            //...
    }
    
    0 讨论(0)
  • 2020-12-04 11:17

    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.

    0 讨论(0)
  • 2020-12-04 11:18
    switch (String.valueOf(value)){
        case "null":
        default: 
    }
    
    0 讨论(0)
提交回复
热议问题