How to check whether an Integer is null or zero in Java? How to check whether an Integer is null or zero in Java? java java

How to check whether an Integer is null or zero in Java?


With Java 8:

if (Optional.ofNullable(myInteger).orElse(0) != 0) {  ...}

Note that Optional may help you to completely avoid the if condition at all, depending on your use case...


Since StringUtils class is mentioned in the question, I assume that Apache Commons lib is already used in the project.

Then you can use the following:

if (0 != ObjectUtils.defaultIfNull(myInteger, 0)) { ... }

Or using static import:

if (0 != defaultIfNull(myInteger, 0)) { ... }


I would use a ternary condition for this. Something like :

public static boolean isNullorZero(Integer i){    return 0 == ( i == null ? 0 : i);}

This is not readable, I agree ;)