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

后端 未结 9 1100
囚心锁ツ
囚心锁ツ 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:27

    According to Java Docs:

    A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).

    Since null has no type, and is not an instance of anything, it will not work with a switch statement.

    0 讨论(0)
  • 2020-12-13 17:30

    In general null is nasty to handle; maybe a better language can live without null.

    Your problem might be solved by

        switch(month==null?"":month)
        {
            ...
            //case "":
            default: 
                monthNumber = 0;
    
        }
    
    0 讨论(0)
  • 2020-12-13 17:30

    I agree with insightful comments (Under the hood ....) in https://stackoverflow.com/a/18263594/1053496 in @Paul Bellora's answer.

    I found one more reason from my experience.

    If 'case' can be null that means switch(variable) is null then as long as the developer provides a matching 'null' case then we can argue it's fine . But what will happen if the developer does not provide any matching 'null' case. Then we have to match it to a 'default' case which may not be what developer has intended to handle in the default case. Therefore matching 'null' to a default could cause 'surprising behaviour'. Therefore throwing 'NPE' will make the developer to handle every cases explicitly. I found throwing NPE in this case very thoughtful.

    0 讨论(0)
提交回复
热议问题