NullPointerException and unboxing

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

The first one is an error that throws a NullPointerException , and the second one works. NPE occurs when getNewIndex assigned the result maxIdx . The question is why?

Invalid NPE throwing option:

 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 someone wonders. I am using Oracle Java 1.8.0_45

+5
java boxing autoboxing
source share
1 answer

Automatic unlocking occurs because 1 sets the result of the triple operation as int.

Integer returned by getNewIndex is null, which causes NPE when unpacking.

Instead, you can use new Integer(1) to avoid unpacking.

+7
source share

All Articles