• Post Reply Bookmark Topic Watch Topic
  • New Topic

return null from primitive method  RSS feed

 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Greg Charles
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The ternary operator is a weird thing. It can cause weird behaviour such as this and this:
 
Greg Charles
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, I see your point. Yes, it unboxes both, converts the int to double, then reboxes both as Double. That is a bit weird.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!