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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With