| Author |
return null from primitive method
|
Sebastian Janisch
Ranch Hand
Joined: Feb 23, 2009
Posts: 1183
|
|
Hey guys,
does anybody know why the compiler doesn't throw bricks at you when doing this:
At runtime, a NullPointerException will be thrown when o is null, but I wonder how come the compiler lets you get away with it.
|
JDBCSupport - An easy to use, light-weight JDBC framework -
|
 |
Greg Charles
Bartender
Joined: Oct 01, 2001
Posts: 2542
|
|
|
Yeah, that's a bit strange. My guess is the compiler sees the object type (null) and so decides it needs to autobox. Both null and the autoboxed true are valid instances of Boolean, so the compiler decides it's OK. On mine, I do get a warning that the unboxing may cause an NPE though.
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
The ternary operator is a weird thing. It can cause weird behaviour such as this and this:
|
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
|
 |
Greg Charles
Bartender
Joined: Oct 01, 2001
Posts: 2542
|
|
Is that weird? That example seems perfectly reasonable to me, much more so than the OP. In fact, if you looked at the byte code, I bet you'd see that the compiler optimized it to:
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
But it is printing "6.0" not "6". Which would be expected with an Integer.
In this case it is partially the fault of autoboxing but it only happens with the ternary operator so I blame the ternary operator.
|
 |
Greg Charles
Bartender
Joined: Oct 01, 2001
Posts: 2542
|
|
|
Oh, I see your point. Yes, it unboxes both, converts the int to double, then reboxes both as Double. That is a bit weird.
|
 |
 |
|
|
subject: return null from primitive method
|
|
|