I have refer to this before posting this Question.
Checking Null Wrappers against primitive values
And I have situation that I want to check Wrapper Integer
with null
as well 0
if( statusId != null || statusId != 0 ) //statusId is Integer it maybe 0 or null
// Do Somethimg here
How can I overcome this situation ?
Replace or
by and
:
if( statusId != null && statusId != 0 )
It will work because only if statusId
is not null
:
statusId != null
you will try to unbox statusId
to int
:
statusId != 0
And in the case of statusId
is null
, the short-circuiting &&
operator will prevent to throw a NullPointerException
as statusId != 0
will not be evaluated.
If you want to get rid of null
check then you can use equals
, e.g.:
Integer i = null;
if(Integer.valueOf(0).equals(i)){
System.out.println("zero");
}else{
System.out.println("not zero");
}
The problem is that you're letting the null through to the second check, and getting a null pointer.
Equivalent working logic:
if (!(statusId == null || statusId == 0)) {
}
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