Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double != null is causing a NullPointerException

I have the following snippet of code that is causing me bother, where currentRate and secondCurrentRate are Double objects, correctly defined:

(currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;

This should check each each Double for null-ness and assign the value null accordingly. However, if secondCurrentRate is null, this causes a NullPointerException. I have changed the snippet to this:

(currentRate == null | secondCurrentRate == null) ? null : currentRate * secondCurrentRate;

And this works as expected. My question is why is this happening? I could understand it if I was calling some method on the objects but my understanding was that NullPointerExceptions were thrown when a method was called on a null object. There is a null object but there is no method call.

Can anyone offer any insight into this? This is running in Java 5.

like image 852
Richard Avatar asked Aug 23 '10 13:08

Richard


2 Answers

I think your problem is elsewhere.

This works :

    Double currentRate=null, secondCurrentRate =null;
    Double test = (currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;

But if you've done this, it will cause a NPE:

    Double currentRate=null, secondCurrentRate =null;
    double test = (currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;
like image 123
Colin Hebert Avatar answered Oct 18 '22 04:10

Colin Hebert


The type of the conditional operator is actually quite complicated. I believe what happens in your first example, is this: The second operand of the conditional,

currentRate * secondCurrentRate

is of type double, and this also becomes the type of the entire expression. Then, when either of the values are null, it tries to set the value of the expression to the Double null, which is unboxed into a double and causes a NPE.

The reason the second expression works is due to slightly different semantics of the conditional expression in this case.

like image 2
waxwing Avatar answered Oct 18 '22 02:10

waxwing