为什么在 Java 中比较 Integer 和 int 会抛出 NullPointerException?

观察这种情况让我非常困惑:

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

因此,我认为首先执行装箱操作(例如,java 尝试从 null中提取 int 值) ,比较操作的优先级较低,这就是抛出异常的原因。

问题是: 为什么它在 Java 中以这种方式实现?为什么拳击的优先级高于比较参考?或者他们为什么没有在拳击之前实现对 null的验证?

目前,当 NullPointerException与包装的原语一起抛出而不是与 没错对象类型一起抛出时,它看起来是不一致的。

42578 次浏览

The Short Answer

The key point is this:

  • == between two reference types is always reference comparison
    • More often than not, e.g. with Integer and String, you'd want to use equals instead
  • == between a reference type and a numeric primitive type is always numeric comparison
    • The reference type will be subjected to unboxing conversion
    • Unboxing null always throws NullPointerException
  • While Java has many special treatments for String, it is in fact NOT a primitive type

The above statements hold for any given valid Java code. With this understanding, there is no inconsistency whatsoever in the snippet you presented.


The Long Answer

Here are the relevant JLS sections:

JLS 15.21.3 Reference Equality Operators == and !=

If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.

This explains the following:

Integer i = null;
String str = null;


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

Both operands are reference types, and that's why the == is reference equality comparison.

This also explains the following:

System.out.println(new Integer(0) == new Integer(0)); // "false"
System.out.println("X" == "x".toUpperCase()); // "false"

For == to be numerical equality, at least one of the operand must be a numeric type:

JLS 15.21.1 Numerical Equality Operators == and !=

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible to numeric type, binary numeric promotion is performed on the operands. If the promoted type of the operands is int or long, then an integer equality test is performed; if the promoted type is float or double`, then a floating-point equality test is performed.

Note that binary numeric promotion performs value set conversion and unboxing conversion.

This explains:

Integer i = null;


if (i == 0) {  //NullPointerException
}

Here's an excerpt from Effective Java 2nd Edition, Item 49: Prefer primitives to boxed primitives:

In summary, use primitives in preference to boxed primitive whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the == operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw NullPointerException. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.

There are places where you have no choice but to use boxed primitives, e.g. generics, but otherwise you should seriously consider if a decision to use boxed primitives is justified.

References

Related questions

Related questions

It's because of Javas autoboxing feature. The compiler detects, that on the right hand side of the comparison you're using a primitive integer and needs to unbox the wrapper Integer value into a primitive int value as well.

Since that's not possible (it's null as you lined out) the NullPointerException is thrown.

Your NPE example is equivalent to this code, thanks to autoboxing:

if ( i.intValue( ) == 0 )

Hence NPE if i is null.

In i == 0 Java will try to do auto-unboxing and do a numerical comparison (i.e. "is the value stored in the wrapper object referenced by i the same as the value 0?").

Since i is null the unboxing will throw a NullPointerException.

The reasoning goes like this:

The first sentence of JLS § 15.21.1 Numerical Equality Operators == and != reads like this:

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

Clearly i is convertible to a numeric type and 0 is a numeric type, so the binary numeric promotion is performed on the operands.

§ 5.6.2 Binary Numeric Promotion says (among other things):

If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed.

§ 5.1.8 Unboxing Conversion says (among other things):

If r is null, unboxing conversion throws a NullPointerException

if (i == 0) {  //NullPointerException
...
}

i is an Integer and the 0 is an int so in the what really is done is something like this

i.intValue() == 0

And this cause the nullPointer because the i is null. For String we do not have this operation, thats why is no exception there.

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 Integer I; int i;0 and Integer I; int i;1 but Integer I; int i;2 [e.g. x=16777216f y=16777216 z=16777217]. It also means that the comparison Integer I; int i;3 is translated as "Convert I to an Integer I; int i;4 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;
}