Why comparing Integer with int can throw NullPointerException in Java?

Viewed 42065

It was very confusing to me to observe this situation:

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
   ...
}

So, as I think boxing operation is executed first (i.e. java tries to extract int value from null) and comparison operation has lower priority that's why the exception is thrown.

The question is: why is it implemented in this way in Java? Why boxing has higher priority then comparing references? Or why didn't they implemented verification against null before boxing?

At the moment it looks inconsistent when NullPointerException is thrown with wrapped primitives and is not thrown with true object types.

7 Answers

The makers of Java could have defined the == operator to directly act upon operands of different types, in which case given Integer I; int i; the comparison I==i; could ask the question "Does I hold a reference to an Integer whose value is i?"--a question which could be answered without difficulty even when I is null. Unfortunately, Java does not directly check whether operands of different types are equal; instead, it checks whether the language allows the type of either operand to be converted to the type of the other and--if it does--compares the converted operand to the non-converted one. Such behavior means that for variables x, y, and z with some combinations of types, it's possible to have x==y and y==z but x!=z [e.g. x=16777216f y=16777216 z=16777217]. It also means that the comparison I==i is translated as "Convert I to an int and, if that doesn't throw an exception, compare it to i."

Simply write a method and call it to avoid NullPointerException.

public static Integer getNotNullIntValue(Integer value)
{
    if(value!=null)
    {
        return value;
    }
    return 0;
}
Related