This question already has an answer here:
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
The auto unboxing happens because the
1
sets the result of the ternary operation to be an int.The
Integer
returned bygetNewIndex
is null, which causes theNPE
when unboxing.You can use
new Integer(1)
instead to avoid the unboxing.