Java ternary operator and NullPointerException -


this question has answer here:

hi,i encountered problem in works,the question this:

integer test1=null; integer test2=null; 

i call them this:

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

then java throw nullpointerexception,so iwrite code this:

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

this code ok.

but,why?

here

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

the expression going return int, not integer.

so jvm unbox test1, , later box result. if unbox null, throw npe.

e.g. try this:

    integer = null;     int b = a; 

you'll npe @ second line. but surely simple integer assignment!? not so. it's unboxing null.

i advise against mixing integers , int when null involved. complete nightmare resolve these issues (i'm looking @ such stuff right involving method calls returning ints , integers, , passing null around. simple method return blows unexpectedly).

if have 'optional' integer result, recommend not using null, , rather sort of optional wrapper.


Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

jquery - How would i go about shortening this code? And to cancel the previous click on click of new section? -