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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With