Search code examples
javaautoboxing

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 ?


Solution

  • 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.