Question

hi,I encountered a problem in works,the question like this:

Integer test1=null;
Integer test2=null;

i call them like this:

test2=(test1==null?test1:(test1+1));
test2=(test1==null?test1:-1);

then the java throw a NullPointerException,so iwrite another code like this:

test2=(test1==null?test1:test1); 

this code is ok.

but,why?

Was it helpful?

Solution

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.

OTHER TIPS

test2=(test1==null?test1:(test1+1));

is equivalent to

   if(test1==null)
{
    test2 = test1;
}

else{

   test2 = test1 + 1;    
}

Please note you can never do any operation on null (Here you are doing test1 + 1 which is equivalent to null + 1 . Hence the Null Pointer Exception)

Happy Coding :)

Do something like:

test2=(test1==null?test1: new Integer(test1+1));
test2=(test1==null?test1: new Integer(-1));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top