views:

155

answers:

2

Hi,

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.

+5  A: 

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;
Colin Hebert
0 down vote I've just tried this and while the compiler doesn't allow double a = null; it will happily let you write double a = 0.0 > 1.0 ? a : null; which will compile but throw NPE. That's psychic power debugging you are doing here ;-)
Gabor Kulcsar
In fact with the ternary operator, the JVM will consider null as a `Double` then unbox it into a `double` and then crash :)
Colin Hebert
+1  A: 

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.

waxwing