Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking Integer Wrapper against NULL as well as primitive value 0

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 ?

like image 505
Shantaram Tupe Avatar asked Jul 24 '17 11:07

Shantaram Tupe


3 Answers

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.

like image 140
davidxxx Avatar answered Oct 31 '22 16:10

davidxxx


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");
}
like image 34
Darshan Mehta Avatar answered Oct 31 '22 16:10

Darshan Mehta


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)) {
}
like image 1
David Lavender Avatar answered Oct 31 '22 16:10

David Lavender