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