NullPointerException and unboxing [duplicate]

2019-06-20 16:54发布

问题:

This question already has an answer here:

  • NullPointerException through auto-boxing-behavior of Java ternary operator 3 answers

I have two almost equal pieces of code (see below) that do NOT work the same, but in my opinion should work the same.

The first one is the buggy version that throws NullPointerException and the second one just works. NPE happens when assigning getNewIndex result to maxIdx. The question is why?

Incorrect version throwing NPE:

Integer maxIdx = fieldName.equals(Fields.KEYS) ? 1 :
            getNewIndex(field.getGroup(), Fields.KEYS, Fields.PARAMS);

And the correct working version:

Integer maxIdx = fieldName.equals(Fields.KEYS) ? 1 : null;
if (maxIdx == null) {
    maxIdx = getNewIndex(field.getGroup(), Fields.KEYS, Fields.PARAMS);
}

And if anyone is wondering. I'm using Oracle Java 1.8.0_45

回答1:

The auto unboxing happens because the 1 sets the result of the ternary operation to be an int.

The Integer returned by getNewIndex is null, which causes the NPE when unboxing.

You can use new Integer(1) instead to avoid the unboxing.