When a variable can only take one out of a small set of possible values, it’s a good idea to use enums in a program. Enum is a special keyword short for enumeration that allows us to create a list of constants grouped by their content: seasons, colors, states, etc. When we store a bunch of constants in one place and handle them together, it helps us to avoid errors, and it makes the code look more readable and clear.

Now, let’s look closer at how enums work.

Defining an enum

We can create our own enumeration in a way that is similar to declaring classes. According to the Java Code Convention, constants in an enum are written in uppercase letters. All constants should be separated with commas. Take a look at the example enum Season:

public enum Season {
    SPRING, SUMMER, AUTUMN, WINTER // four instances
}

It is possible to declare an enum inside the class. In this case, we don’t need to use public modifier in the enum declaration.

In general, an enum can be considered as a class with predefined instances. Here, we have four instances of seasons SPRINGSUMMERAUTUMN and WINTER inside the storage Season. If we want to extend the list of constants, we can simply add another instance in our enum: mid-winter, Australian winter, etc. Don’t forget that in real life they have to make sense.

Now that we’ve got an idea of how to define basic enums, let’s learn how to use them in a program.

Methods for processing enums

Suppose that we have to write a program with an enum that displays three possible user statuses. Let’s create an enum UserStatus with these statuses:

public enum UserStatus {
    PENDING, ACTIVE, BLOCKED
}

And now we initialize a variable of the type UserStatus from the previous example:

UserStatus active = UserStatus.ACTIVE;

Each enum value has a name that can be accessed by using the method name():

System.out.println(active.name()); // ACTIVE

Sometimes, we may need to access an enumeration instance by its name. This can be done with the valueOf() method which provides us with another way to initialize a variable:

UserStatus blocked = UserStatus.valueOf("BLOCKED"); // BLOCKED

An important thing to remember about this method is that it is case-sensitiveThat means that if the given string doesn’t exactly match any constant, we will get an IllegalArgumentException.

UserStatus blocked = UserStatus.valueOf("blocked"); // IllegalArgumentException, valueOf is case-sensitive

If we want to look at all constants of an enumeration, we can get them in an array by using the values() method:

UserStatus[] statuses = UserStatus.values(); // [PENDING, ACTIVE, BLOCKED]

Another method called ordinal() returns the ordinal position of an instance of an enum:

System.out.println(active.ordinal()); // 1 (starting with 0)
System.out.println(UserStatus.BLOCKED.ordinal()); // 2

Although an enum is a reference type, two variables can be correctly compared by using both the equals method and the operator ==.

System.out.println(active.equals(UserStatus.ACTIVE)); // true
System.out.println(active == UserStatus.ACTIVE); // true

Enumerations in the switch statement

An enum can be successfully used in the switch statement. Depending on the status, our program can perform different actions indicated by the switch statement. In this case, it prints out different responses:

UserStatus status = ... // some status
 
switch (status) {
    case PENDING:
        System.out.println("You need to wait a little.");
        break;
    case ACTIVE:
        System.out.println("No problems, you may pass here.");
        break;
    case BLOCKED:
        System.out.println("Stop! You can't pass here.");
        break;
    default:
        System.out.println("Unsupported enum constant.");
}

The message that our program outputs depends on the value of the variable status.

Iterating over an enum

One of the best ways to iterate over an enum is to use a for or a for-each loop. Let’s apply it to our sample enum:

    for (UserStatus status : UserStatus.values()) {
        System.out.println(status);
    }
/* the output is
PENDING 
ACTIVE
BLOCKED
*/
        

Here, we used the values() method to return an array of enum values. This loop comes in handy when iterating over enums with a large number of constants.

Conclusion

An enum is a special keyword that helps us to define named constants grouped together according to their content. By defining enums you can make code more readable and avoid invalid values being passed in.
The number of constants in an enum may be extended whenever we want. Also, you can use the name()valueOf()ordinal() and equals() methods to process the enum. switch statements and for-each loops are widely used while working with enums in simple programs.

Now you know how to use it, so get ready for some practice!

Leave a Reply

Your email address will not be published.