简体   繁体   中英

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

Is there more concise way to write:

if (myInteger != null && myInteger != 0) { ... }

For example, for Strings you can use StringUtils.isBlank()

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 ;)

I created a helper method that maybe can help you, it uses reflection so you have to think if is necessary to use it, also you need java 8.

The method is for all java numbers:

 public class NumberUtils {

    private NumberUtils(){
    }

    public static  < T extends Number>  T getNumberOrZero(T number, Class<? extends Number> clazz) {
        return Optional.ofNullable(number)
                .orElse(getZeroValue(clazz));
    }

    @SuppressWarnings("unchecked")
    private static < T extends Number> T getZeroValue( Class<? extends Number> clazz){
        try{
            Constructor<? extends Number> constructor = clazz.getDeclaredConstructor(String.class);
            return (T) constructor.newInstance("0");
        }catch (ReflectiveOperationException e) {
            throw new IllegalArgumentException("Can't get zero value ", e);
        }
    }
}

You can call in this way:

Integer myNumber = NumberUtils.getNumberOrZero(someIntegerThatCanBeNull, Integer.class);

I hope this can help you.

private boolean isNullOrZero(Integer i){
     return i == null || i.intValue() == 0;
}

For some other types:

i.longValue() == 0 for Long

i.doubleValue() == 0 for Double

i.shortValue() == 0 for Short

i.floatValue() == 0 for Float

Depending on your implementation of myInteger (ie if the Integer property within myInteger is the box type Integer or the unboxed primitive int ), you may only have to write one conditional.

Integer s are actual objects, which means they have the ability to be null . That being said they can also hold 0 as a value. So, in this case you would have to make both checks.

int is a primitive and cannot hold the value of null . In this case you would only have to check if your int property is not equal to 0.

There is alwo a nullsafe way to do it like:

Long val = null;
if( val == Long.valueOf( 0 ) ) {...}

or

if( Objects.equals( val, 0L ) ) {...}

ObjectUtils.nullSafeEquals(0, myInteger) would be good to use if you don't want to increase cyclomatic complexity AND still get the functionality of myInteger.equals(0) while handling null values appropriatly.

private boolean isNotNullAndZero(Long num){
        return Optional.ofNullable(num).orElse(0L) != 0L ? true:false;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM