I investigated helpful NullPointerExceptions from Java 14 and tested different scenarios. Surprisingly, unboxing seems to lead to helfpul NPEs in some scenarios, whereas other scenarios do not contain any error message:
// NPE with message 'Cannot invoke "java.lang.Integer.intValue()" because "index" is null'
Integer index = null;
int i = index;
// NPE with message null
List.of('a', 'b', 'c').indexOf(index);
I wonder, why the second example does not lead to the same message as the first one. I read JEP 358 and learned that the message is comuputed based on the byte code instructions. Are they different for these two scenrios? I expected both snearios to call Integer.intValue() to unbox the value.
(Tested with Oracle JDK 17.0.4.1)
CodePudding user response:
The reason is because the cause is different. The List
created by List.of
doesn't allow nulls, and when indexOf
receives a null
, it simply throws a NullPointerException
without a message:
@Override
public int indexOf(Object o) {
if (!allowNulls && o == null) {
throw new NullPointerException();
}
Object[] es = elements;
for (int i = 0; i < es.length; i ) {
if (Objects.equals(o, es[i])) {
return i;
}
}
return -1;
}
(from the java.util.ImmutableCollections.ListN
class)
On the other hand, in the case of int i = index;
it is compiled to the equivalent of int i = index.intValue();
, and the JVM generates the message of the NullPointerException
based on the method calls and variables involved.