How do I define and use an enum in Java?

An enum defines a fixed set of named constants. You can use it to represent values such as order statuses, directions, or days of the week.

In this example, you will define an enum for order statuses and use a switch expression to select a message.

Source code

Save the following code as EnumExample.java:

public class EnumExample {
    void main() {
        OrderStatus status = OrderStatus.SHIPPED;

        String message = switch (status) {
            case PENDING -> "Your order is waiting for confirmation.";
            case PROCESSING -> "Your order is being prepared.";
            case SHIPPED -> "Your order is on its way.";
            case DELIVERED -> "Your order has arrived.";
        };

        IO.println("Current status: " + status);
        IO.println("Message: " + message);

        IO.println();
        IO.println("Available statuses:");

        for (OrderStatus availableStatus : OrderStatus.values()) {
            IO.println(availableStatus);
        }
    }
}

enum OrderStatus {
    PENDING,
    PROCESSING,
    SHIPPED,
    DELIVERED
}

Explanation

The enum keyword declares a type with a fixed set of constants:

enum OrderStatus {
    PENDING,
    PROCESSING,
    SHIPPED,
    DELIVERED
}

Enum constant names conventionally use uppercase letters, with underscores separating words.

Assigning an enum value

Use the enum type followed by a constant name:

OrderStatus status = OrderStatus.SHIPPED;

The variable status can hold a reference to an OrderStatus constant. You cannot assign a string such as "SHIPPED" directly to it.

This helps prevent mistakes caused by spelling or capitalization differences in string values.

Using an enum in a switch expression

The switch expression selects a message for the current status:

String message = switch (status) {
    case PENDING -> "Your order is waiting for confirmation.";
    case PROCESSING -> "Your order is being prepared.";
    case SHIPPED -> "Your order is on its way.";
    case DELIVERED -> "Your order has arrived.";
};

Inside these case labels, you can use the constant names without the OrderStatus. prefix.

The expression covers every constant declared in OrderStatus, so a default rule is unnecessary.

Looping through enum constants

Every enum provides a values() method that returns an array of its constants in declaration order:

for (OrderStatus availableStatus : OrderStatus.values()) {
    IO.println(availableStatus);
}

Here, the loop prints all four statuses, starting with PENDING.

Run the example

Compile and run the file:

javac EnumExample.java
java EnumExample

Output

Current status: SHIPPED
Message: Your order is on its way.

Available statuses:
PENDING
PROCESSING
SHIPPED
DELIVERED

Use an enum when a value should come from a known set of choices. It gives those choices meaningful names and lets the compiler check their usage.

How do I pick a random value from an enum?

The following code snippet will show you how to pick a random value from an enum. First we’ll create an enum called BaseColor which will have three valid value. These values are Red, Green and Blue.

To allow us to get random value of this BaseColor enum we define a getRandomColor() method in the enum. This method use the java.util.Random to create a random value. This random value then will be used to pick a random value from the enum.

Let’s see the code snippet below:

package org.kodejava.basic;

import java.util.Random;

public class EnumGetRandomValueExample {
    public static void main(String[] args) {
        // Pick a random BaseColor for 10 times.
        for (int i = 0; i < 10; i++) {
            System.out.printf("color[%d] = %s%n", i,
                    BaseColor.getRandomColor());
        }
    }

    /**
     * BaseColor enum.
     */
    private enum BaseColor {
        Red,
        Green,
        Blue;

        /**
         * Pick a random value of the BaseColor enum.
         *
         * @return a random BaseColor.
         */
        public static BaseColor getRandomColor() {
            Random random = new Random();
            return values()[random.nextInt(values().length)];
        }
    }
}

The output of the code snippet:

color[0] = Green
color[1] = Green
color[2] = Blue
color[3] = Red
color[4] = Blue
color[5] = Blue
color[6] = Blue
color[7] = Blue
color[8] = Green
color[9] = Blue

How do I get name of enum constant?

This example demonstrate how to user enum‘s name() method to get enum constant name exactly as declared in the enum declaration.

package org.kodejava.basic;

enum ProcessStatus {
    IDLE, RUNNING, FAILED, DONE;

    @Override
    public String toString() {
        return "Process Status: " + this.name();
    }
}

public class EnumNameDemo {
    public static void main(String[] args) {
        for (ProcessStatus processStatus : ProcessStatus.values()) {
            // Gets the name of this enum constant, exactly as
            // declared in its enum declaration.
            System.out.println(processStatus.name());

            // Here we call to our implementation of the toString
            // method to get a more friendly message of the
            // enum constant name.
            System.out.println(processStatus);
        }
    }
}

Our program result:

IDLE
Process Status: IDLE
RUNNING
Process Status: RUNNING
FAILED
Process Status: FAILED
DONE
Process Status: DONE

How do I get ordinal value of enum constant?

This example demonstrate the use of enum ordinal() method to get the ordinal value of an enum constant.

package org.kodejava.basic;

enum Color {
    RED, GREEN, BLUE
}

public class EnumOrdinal {
    public static void main(String[] args) {
        // Gets the ordinal of this enumeration constant (its
        // position in its enum declaration, where the initial 
        // constant is assigned an ordinal of zero)
        System.out.println("Color.RED  : " + Color.RED.ordinal());
        System.out.println("Color.GREEN: " + Color.GREEN.ordinal());
        System.out.println("Color.BLUE : " + Color.BLUE.ordinal());
    }
}

The program print the following result:

Color.RED  : 0
Color.GREEN: 1
Color.BLUE : 2

How do I define a field in enum type?

As we know that Java enumeration type is powerful compared to enum implementation in other programming language. Basically enum is class typed, so it can have constructors, methods and fields.

In the example below you’ll see how a field is defined in an enumeration type. Because each constant value for the Fruit enum is a type of Fruit itself it will have its own price field. The price field holds a unique value for each constant such as APPLE, ORANGE, etc.

In the result you’ll see that the constructor will be called for each constant value and initialize it with the value passed to the constructor.

package org.kodejava.basic;

enum Fruit {
    APPLE(1.5f), ORANGE(2), MANGO(3.5f), GRAPE(5);

    private final float price;

    Fruit(float price) {
        System.out.println("Name: " + this.name() + " initialized.");
        this.price = price;
    }

    public float getPrice() {
        return this.price;
    }
}

public class EnumFieldDemo {
    public static void main(String[] args) {
        // Get the name and price of all enum constant value.
        for (Fruit fruit : Fruit.values()) {
            System.out.printf("Fruit = %s; Price = %5.2f%n",
                    fruit.name(), fruit.getPrice());
        }
    }
}

Our demo result is below:

Name: APPLE initialized.
Name: ORANGE initialized.
Name: MANGO initialized.
Name: GRAPE initialized.
Fruit = APPLE; Price =  1.50
Fruit = ORANGE; Price =  2.00
Fruit = MANGO; Price =  3.50
Fruit = GRAPE; Price =  5.00