NullPointerException through auto-boxing-behavior of Java ternary operator -


i tripped across strange nullpointerexception other day caused unexpected type-cast in ternary operator. given (useless exemplary) function:

integer getnumber() {     return null; } 

i expecting following 2 code segments identical after compilation:

integer number; if (condition) {     number = getnumber(); } else {     number = 0; } 

vs.

integer number = (condition) ? getnumber() : 0; 

.

turns out, if condition true, if-statement works fine, while ternary opration in second code segment throws nullpointerexception. seems though ternary operation has decided type-cast both choices int before auto-boxing result integer!?! in fact, if explicitly cast 0 integer, exception goes away. in other words:

integer number = (condition) ? getnumber() : 0; 

is not same as:

integer number = (condition) ? getnumber() : (integer) 0; 

.

so, seems there byte-code difference between ternary operator , equivalent if-else-statement (something didn't expect). raises 3 questions: why there difference? bug in ternary implementation or there reason type cast? given there difference, ternary operation more or less performant equivalent if-statement (i know, difference can't huge, still)?

according jls: -

the type of conditional expression determined follows:

  • if second , third operands have same type (which may null type), type of conditional expression.
  • if 1 of second , third operands of primitive type t, , type of other result of applying boxing conversion
    (§5.1.7) t, type of conditional expression t.

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -