Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null pointer exception from an inline conditional statement

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?

like image 799
Andrew K Avatar asked Jul 15 '26 04:07

Andrew K


2 Answers

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.

like image 116
Rocky Pulley Avatar answered Jul 18 '26 18:07

Rocky Pulley


It's attempting to unbox the reference test to get the long value, which it cannot do.

like image 27
CassOnMars Avatar answered Jul 18 '26 18:07

CassOnMars



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!