I'm getting a bizarre null pointer exception and I can't understand why. I narrowed it down with this simple test code, which throws an NPE on the second line:
Long test = null;
Long result = true ? test : -1L;
While this code works fine:
Long result = true ? null : -1L;
This is easy enough to avoid by just not using an inline conditional statement, but can anyone explain to me why this is happening?
I think this comes down to unboxing. The following code will work:
Long two = true ? test : new Long(-1);
If one parameter is just -1 then it will try to unbox test so it treats both as the same type. Unboxing null will cause the null pointer exception. If it's null specifically in the statement, it will be smart enough to not try to unbox that.
It's attempting to unbox the reference test to get the long value, which it cannot do.
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