There are plenty of good 'classic' Java answers in this thread already, so for the sake of it... here's a Java 8 one: use OptionalInt
.
Assuming statusId
is an OptionalInt
, you would write:
if(statusId.isPresent() && statusId.getAsInt() != 0)
Or slightly more cryptically, you could do this:
if(statusId.orElse(0) != 0)
In this scenario, statusId
is never set to null; instead it is set to either a OptionalInt.of(<some int>)
, OptionalInt.ofNullable(<some Integer>)
or OptionalInt.empty()
.
The point of this answer is that as of Java 8, the standard library offers convenient Optional
and related classes for primitives to write null-safe Java code. You might want to check them out. Optional
is especially handy, because of its filter
and map
methods.