Checking to see if a an Enum is null or empty

Shaun picture Shaun · Mar 30, 2015 · Viewed 32.4k times · Source

I am trying to validate a json that is being sent into my controller and I am using the BindingResult way and I am able to validate strings and everything else fine as normal. But im not sure how to check if an Enum is empty or null.

Answer

Rene M. picture Rene M. · Mar 30, 2015

First of all an Enum can't be empty! It is an Object representing a defined state. Think of it like an static final Object which can't be changed after intialization, but easyly compared.

So what you can do is check on null and on Equals to your existing Enum Values.

On request here basics about Enum compare:

public enum Currency {PENNY, NICKLE, DIME, QUARTER};

Currency coin = Currency.PENNY;
Currency noCoin = null
Currency pennyCoin = Currency.PENNY;
Currency otherCoin = Currency.NICKLE;

if (coin != null) {
    System.out.println("The coin is not null");
}

if (noCoin == null) {
    System.out.println("noCoin is null");
}

if (coin.equals(pennyCoin)) {
    System.out.println("The coin is a penny, because its equals pennyCoin");
}

if (coin.equals(Currency.PENNY)) {
    System.out.println("The coin is a penny, because its equals Currency.PENNY");
}

if (!coin.equals(otherCoin)) {
    System.out.println("The coin is not an otherCoin");
}

switch (coin) {
    case PENNY:
        System.out.println("It's a penny");
        break;
    case NICKLE:
        System.out.println("It's a nickle");
        break;
    case DIME:
        System.out.println("It's a dime");
        break;
    case QUARTER:
        System.out.println("It's a quarter");
        break;
}

Output: "It's a penny"