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
nullswitch label prevents 1 writing code can never executed. ifswitchexpression of reference type, is,stringor boxed primitive type or enum type, run-time error occur if expression evaluatesnull@ run time. in judgment of designers of java programming language, better outcome silently skipping entireswitchstatement or choosing execute statements (if any) afterdefaultlabel (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,
switchstatement typically compile tablesswitch byte code. , "physical" argumentswitchcasesints. int value switch on determined invoking methodenum.ordinal(). [...] ordinals start @ zero.that means, mapping
null0wouldn'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
Post a Comment