This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: Why does comparing an Integer to an int throw a NullPointerException in Java?

It puzzled me to see this happen:

Integer i = null;
String str = null;

if (i == null) {   //Nothing happens. }if (str == null) { //Nothing happens

}

if (i == 0) {  //NullPointerException. }if (str == "0") { //Nothing happens. }Copy the code

So, I think the boxing operation is done first (that is, Java tries to extract an int from NULL) and the comparison operation has a lower priority, which is why the exception is thrown.

The question is: why is it implemented this way in Java? Why does the boxing operation have higher priority than the referenced comparison operation? Or why don’t they implement null validation before boxing?

For now, however, it looks inconsistent because NullPointerException is thrown when the container is being loaded instead of when the actual object type is being used.

Answer a

Java authors define the == operator to operate directly on operands of different types, in this case given Integer I; int i; Is I = = I; Someone will ask the question, “Am I holding an Integer type that references the value I?” This problem is easy even if I is null. Unfortunately, Java does not directly check whether operands of different types are equal; Instead, it checks whether the Java language allows the type of any operand to be converted to the type of another operand and, if so, compares the converted operand to the unconverted operand. This behavior means that for some type combinations of variables x, y, and z, there can be x==y and y==z, but x! Z = (such as. X = 16777216f Y = 16777216 z = 16777216]. This also means that comparing I== I is translated as “convert I to int and compare it to I if no exception is thrown.

The article translated from Stack Overflow:stackoverflow.com/questions/3…