Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I compare null field to a primitive [duplicate]

Tags:

java

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.

like image 869
Михаил Федосеев Avatar asked Dec 06 '25 04:12

Михаил Федосеев


1 Answers

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

like image 182
Eran Avatar answered Dec 07 '25 19:12

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!