Why doesn't String switch statement support a null case?

后端 未结 9 1138
囚心锁ツ
囚心锁ツ 2020-12-13 16:41

I am just wondering why the Java 7 switch statement does not support a null case and instead throws NullPointerException? See the comm

9条回答
  •  无人及你
    2020-12-13 17:20

    It isn't pretty, but String.valueOf() allows you to use a null String in a switch. If it finds null, it converts it to "null", otherwise it just returns the same String you passed it. If you don't handle "null" explicitly, then it will go to default. The only caveat is that there is no way of distinguishing between the String "null" and an actual null variable.

        String month = null;
        switch (String.valueOf(month)) {
            case "january":
                monthNumber = 1;
                break;
            case "february":
                monthNumber = 2;
                break;
            case "march":
                monthNumber = 3;
                break;
            case "null":
                monthNumber = -1;
                break;
            default: 
                monthNumber = 0;
                break;
        }
        return monthNumber;
    

提交回复
热议问题