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


i wondering why java 7 switch statement not support null case , instead throws nullpointerexception? see commented line below (example taken the java tutorials article on switch):

{     string month = null;     switch (month) {         case "january":             monthnumber = 1;             break;         case "february":             monthnumber = 2;             break;         case "march":             monthnumber = 3;             break;         //case null:         default:              monthnumber = 0;             break;     }      return monthnumber; } 

this have avoided if condition null check before every switch use.

as damryfbfnetsi points out in comments, jls §14.11 has following note:

the prohibition against using null switch label prevents 1 writing code can never executed. if switch expression of reference type, is, string or boxed primitive type or enum type, run-time error occur if expression evaluates null @ run time. in judgment of designers of java programming language, better outcome silently skipping entire switch statement or choosing execute statements (if any) after default label (if any).

(emphasis mine)

while last sentence skips on possibility of using case null:, seems reasonable , offers view language designers' intentions.

if rather @ implementation details, this blog post christian hujer has insightful speculation why null isn't allowed in switches (although centers on enum switch rather string switch):

under hood, switch statement typically compile tablesswitch byte code. , "physical" argument switch cases ints. int value switch on determined invoking method enum.ordinal(). [...] ordinals start @ zero.

that means, mapping null 0 wouldn't idea. switch on first enum value indistinguishible null. maybe would've been idea start counting ordinals enums @ 1. hasn't been defined that, , definition can not changed.

while string switches are implemented differently, enum switch came first , set precedent how switching on reference type should behave when reference null.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -