1

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?

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
xiaoyang
  • 73
  • 4

3 Answers3

7

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.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
2
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 :)

Abhishek Singh
  • 10,243
  • 22
  • 74
  • 108
0

Do something like:

test2=(test1==null?test1: new Integer(test1+1));
test2=(test1==null?test1: new Integer(-1));
blackSmith
  • 3,054
  • 1
  • 20
  • 37