How to use null in switch

前端 未结 12 1061
南方客
南方客 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.
    

提交回复
热议问题