Here
test2=(test1==null?test1:(test1+1));
the expression is going to return an int
, not an Integer
.
So the JVM will unbox test1
, and later box the result. If you unbox a null
, it will throw an NPE.
e.g. try this:
Integer a = null;
int b = a;
You'll get an NPE at the second line. But surely this is a simple integer assignment!? Not so. It's unboxing the null.
I would strongly advise against mixing Integers
and int
when null
is involved. It is a complete nightmare to resolve these issues (I'm looking at such stuff right now involving method calls returning ints
and Integers
, and passing null around. A simple method return blows up unexpectedly).
If you have an 'optional' integer result, then I would recommend not using null, and rather some sort of Optional wrapper.