java - Booleans, conditional operators and autoboxing -


why throw nullpointerexception

public static void main(string[] args) throws exception {     boolean b = true ? returnsnull() : false; // npe on line.     system.out.println(b); }  public static boolean returnsnull() {     return null; } 

while doesn't

public static void main(string[] args) throws exception {     boolean b = true ? null : false;     system.out.println(b); // null } 

?

the solution way replace false boolean.false avoid null being unboxed boolean --which isn't possible. isn't question. question why? there references in jls confirms behaviour, of 2nd case?

the difference explicit type of returnsnull() method affects static typing of expressions @ compile time:

e1: `true ? returnsnull() : false` - boolean (auto-unboxing 2nd operand boolean)  e2: `true ? null : false` - boolean (autoboxing of 3rd operand boolean) 

see java language specification, section 15.25 conditional operator ? :

  • for e1, types of 2nd , 3rd operands boolean , boolean respectively, clause applies:

    if 1 of second , third operands of type boolean , type of other of type boolean, type of conditional expression boolean.

    since type of expression boolean, 2nd operand must coerced boolean. compiler inserts auto-unboxing code 2nd operand (return value of returnsnull()) make type boolean. of course causes npe null returned @ run-time.

  • for e2, types of 2nd , 3rd operands <special null type> (not boolean in e1!) , boolean respectively, no specific typing clause applies (go read 'em!), final "otherwise" clause applies:

    otherwise, second , third operands of types s1 , s2 respectively. let t1 type results applying boxing conversion s1, , let t2 type results applying boxing conversion s2. type of conditional expression result of applying capture conversion (§5.1.10) lub(t1, t2) (§15.12.2.7).

    • s1 == <special null type> (see §4.1)
    • s2 == boolean
    • t1 == box(s1) == <special null type> (see last item in list of boxing conversions in §5.1.7)
    • t2 == box(s2) == `boolean
    • lub(t1, t2) == boolean

    so type of conditional expression boolean , 3rd operand must coerced boolean. compiler inserts auto-boxing code 3rd operand (false). 2nd operand doesn't need auto-unboxing in e1, no auto-unboxing npe when null returned.


this question needs similar type analysis:

java conditional operator ?: result type


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -