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 coercedboolean
. compiler inserts auto-unboxing code 2nd operand (return value ofreturnsnull()
) make typeboolean
. of course causes npenull
returned @ run-time.for e2, types of 2nd , 3rd operands
<special null type>
(notboolean
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 coercedboolean
. compiler inserts auto-boxing code 3rd operand (false
). 2nd operand doesn't need auto-unboxing ine1
, no auto-unboxing npe whennull
returned.- s1 ==
this question needs similar type analysis:
Comments
Post a Comment