Java Enum

Summary: in this tutorial, you’ll learn about Java enum and how to use it effectively to make your code more readable and concise.

Introduction to the Java enum type

In Java, an enum (short for “enumeration”) is a special type that represents a fixed set of related constant values.

To declare an enum, you use the enum keyword followed by the enum’s name, and a pair of curly braces contains its constants:

enum MyEnum {
   VALUE1, VALUE2,...
};Code language: Java (java)

By convention, the enum’s constants are uppercase. The enum keyword denotes that it is a special type of class that extends the java.lang.Enum class:

It means that MyEnum inherits all methods of the Enum class. We’ll cover some of them shortly. In addition, enums may have methods and constructors like regular classes.

For example, the following declares an enum that represents the days of the week:

enum Day {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}Code language: Java (java)

In this example, we declare the Day enum that includes seven constants, each representing the day of the week.

All constants, which you declare in an enum, are instances of the enum class. They are implicitly static, public, and final:

  • static: You can access constants by their names via the enum name e.g., Day.MONDAY.
  • public: You can access the enum’s constants from any part of the program.
  • final: You cannot modify enum constants.

For example, the following declares a variable day with the type Day enum:

Day day;Code language: Java (java)

It’s possible to declare and initialize a value to an enum’s variable at the same time like this:

Day day = Day.MONDAY;Code language: Java (java)

Because Java can infer the type of the day variable, you can use the var keyword as follows:

var day = DAY.MONDAY;Code language: Java (java)

The following example illustrates that constants declared in an enum are instances of the enum:

Day day = Day.MONDAY;
boolean result = Day.MONDAY instanceof Day;
System.out.println(result); // trueCode language: Java (java)

Comparing enum constants using == operator

For a given enum type, Java ensures that there will be a unique instance for each constant value in Java Virtual Machine (JVM). For example, in the Day enum, there is only one instance of the Day.MONDAY in the JVM.

Because of the uniqueness of enum instances, you can safely use the == operator to check if two variables reference the same instance of the enum constant.

The following example illustrates how to use the == operator to compare two enum constants:

public class App {
    public static void main(String[] args) {
        enum Day {
            SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
        }
        var day1 = Day.MONDAY;
        var day2 = Day.MONDAY;
        var day3 = Day.TUESDAY;

        var result = day1 == day2;
        System.out.println(result); // true

        result = day1 == day3;
        System.out.println(result); // false
    }
}Code language: Java (java)

The == operator also provides compile-time and run-time safety.

At compile time, the Java compiler checks if you are comparing values of incompatible types and issue an error. For example:

var day = Day.MONDAY;

if (day == "MONDAY") { // error
    // ..
}Code language: Java (java)

In this example, we attempted to compare the enum constant with a string literal and got an error by the Java compiler.

At runtime, because of the unique instances, the == operator is guaranteed to be accurate and reliable:

var day = Day.MONDAY;
if (day == Day.FRIDAY) {
    //
}Code language: Java (java)

Examining enum member positions

Each constant that you declare in an enum is associated with an integer value. The integer value represents the order in which you declare the constant. The first constant is 0, the second constant is 1, and so on.

To get the position of a constant, you call the ordinal() method inherited from the java.lang.Enum class.

For example, the following uses the ordinal() method to get the position of the SUNDAY and MONDAY constants in the Day enum:

public class App {

    public static void main(String[] args) {
        enum Day {
            SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
        }
        var day = Day.SUNDAY;
        System.out.println(day.ordinal()); // 0

        day = Day.MONDAY;
        System.out.println(day.ordinal()); // 1

    }
}Code language: Java (java)

In practice, you will rarely use the ordinal() method. It is designed for use by enum-based data structures including EnumSet and EnumMap.

Iterating over enum members

The Enum class provides a static method values() that returns an array containing all values of the enum in the order that is declared in the enum definition.

The following example shows how to use the values() method with a foreach statement to iterate all enum constants:

public class App {
    public static void main(String[] args) {
        enum Day {
            SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
        }
        Day[] allDays = Day.values();

        for (Day day : allDays) {
            System.out.println(day);
        }
    }
}Code language: Java (java)

Using Java enum in a switch statement & expression

In practice, you often use enums with the switch statement to make your code more readable and less error-prone. For example:

public class App {
    public static void main(String[] args) {
        enum Day {
            SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
        }

        Day day = Day.MONDAY;

        switch (day) {
            case MONDAY:
            case TUESDAY:
            case WEDNESDAY:
            case THURSDAY:
            case FRIDAY:
                System.out.println("It's a weekday.");
                break;
            case SATURDAY:
            case SUNDAY:
                System.out.println("It's a weekend.");
                break;
        }
    }
}Code language: Java (java)

Output:

It's a weekday.Code language: Java (java)

How it works.

First, declare an enum variable day and initialize its value to Day.MONDAY.

Second, determine whether it is a weekday or weekend by using a switch statement to compare the enum variable with the enum’s members.

Starting from Java 12, you can use enums in switch expressions to make your code more concise:

public class App {
    public static void main(String[] args) {
        enum Day {
            SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
        }

        Day day = Day.MONDAY;

        switch (day) {
            case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> System.out.println("It's a weekday.");
            case SATURDAY, SUNDAY -> System.out.println("It's a weekend.");
        }
    }
}Code language: Java (java)

Summary

  • Use enums when you have a fixed set of related constants.
  • Use enums in switch statements or switch expressions to enhance code readability.