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:
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.