Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparison Integer object with primitive int

Tags:

java

I am comparing integer object with primitive int but getting null pointer exception if Integer object is null

public static void main(String[] args) {

        Integer a = null;
        int b = 1;

        if (a != b) {
            System.out.println("True");
        }

    }


Output : Exception in thread "main" java.lang.NullPointerException
    at com.nfdil.loyalty.common.Test.main(Test.java:10)

I am getting this because its trying to convert null integer object (a.intValue()) into primitive int.

Is there any other way to avoid this?

like image 574
Shiladittya Chakraborty Avatar asked Dec 14 '22 16:12

Shiladittya Chakraborty


1 Answers

You can use Objects.equals:

if (a == null || ! Objects.equals(a, b)) { ... }
like image 182
Ousmane D. Avatar answered Dec 16 '22 06:12

Ousmane D.