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?
You can use Objects.equals
:
if (a == null || ! Objects.equals(a, b)) { ... }
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