2

Could you please tell me why I get a NullPointerException here?

public class N {
    private Integer n = null;
    public static void main(String... wargh) {
        N obj = new N();
        System.out.println(obj.n == 1);
    }
}

The obj.n is (obviously!) null here, so obj.n == 1 must return false - just the same way as null == 1 returns false. But it does not. Instead, it throws an exception.

Farvardin
  • 5,336
  • 5
  • 33
  • 54
  • 3
    primitives can not possibly have a 'null' value, this is only possible for objects. Just so you know: Integer is not a primitive – Stultuske Feb 19 '18 at 12:10

2 Answers2

5

null cannot be compared to a primitive, since a primitive can never be equal to null.

null == 1 doesn't return false - it doesn't pass compilation.

Comparing an Integer to an int requires unboxing of the Integer into an int. obj.n == 1 throws NullPointException when obj.n == null, since unboxing obj.n is equivalent to executing obj.n.intValue().

Eran
  • 387,369
  • 54
  • 702
  • 768
2

Because obj.n == 1 is interpreted as primitive integer comparison, so obj.n will be auto-unboxed calling out.n.intValue(), which leads to the exception.

Formally, JLS 15.21 makes it clear that compiler knows your code is a numeric comparison, and then JLS 15.21.1 applies which states:

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

Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).

Community
  • 1
  • 1
Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43