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.example.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] = Blue
color[1] = Red
color[2] = Red
color[3] = Green
color[4] = Blue
color[5] = Blue
color[6] = Green
color[7] = Red
color[8] = Red
color[9] = Green

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.example.fundamental;

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 ps : ProcessStatus.values()) {
            // Gets the name of this enum constant, exactly as
            // declared in its enum declaration.
            System.out.println(ps.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(ps.toString());
        }
    }
}

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.example.fundamental;

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.example.fundamental;

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

    private 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 f : Fruit.values()) {
            System.out.println("Fruit = " + f.name() + "; Price = " + f.getPrice());
        }
    }
}

Our demo result is below:

Name: APPLE initialized.
Name: ORANGE initialized.
Name: MANGGO initialized.
Name: GRAPE initialized.
Fruit = APPLE; Price = 1.5
Fruit = ORANGE; Price = 2.0
Fruit = MANGGO; Price = 3.5
Fruit = GRAPE; Price = 5.0

How do I get enum constant value corresponds to a string?

The valueOf() method of an enum type allows you to get an enum constant that the value corresponds to the specified string. When we pass a string that not available in the enum an exception will be thrown.

package org.kodejava.example.fundamental;

enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

public class EnumValueOfTest {
    public static void main(String[] args) {
        // Using valueOf() method we can get an enum constant whose
        // value corresponds to the string passed as the parameter.
        Day day = Day.valueOf("SATURDAY");
        System.out.println("Day = " + day);
        day = Day.valueOf("WEDNESDAY");
        System.out.println("Day = " + day);

        try {
            // The following line will produce an exception because the
            // enum type does not contains a constant named JANUARY.
            day = Day.valueOf("JANUARY");
            System.out.println("Day = " + day);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
}

How do I get constants name of an enum?

To get the constants name of an enumeration you can use the values() method of the enumeration type. This method return an array that contains a list of enumeration constants.

package org.kodejava.example.fundamental;

enum Month {
    JANUARY,
    FEBRUARY,
    MARCH,
    APRIL,
    MAY,
    JUNE,
    JULY,
    AUGUST,
    SEPTEMBER,
    OCTOBER,
    NOVEMBER,
    DECEMBER
}

public class EnumValuesTest {
    public static void main(String[] args) {
        // values() method return an array that contains a list of the
        // enumeration constants.
        Month[] months = Month.values();
        System.out.println("Month size: " + months.length);

        // We can user for each statement to print each enumeration
        // constant.
        for (Month month : Month.values()) {
            System.out.println("Month: " + month);
        }
    }
}

How do I define constructor in enum type?

In the following example you’ll see how to add a constructor to an enum type value. Because an enum is just another class type it can have constructors, fields and methods just like any other classes. Below we define a constructor that accept a string value of color code. Because our enum now have a new constructor declared we have to define the constant named value as RED("FF0000"), ORANGE("FFA500"), etc.

In Java enumeration expanded beyond just as a named constants. Because enum is a class type we can add methods, fields and constructors to the enum type as you can see in the example below.

package org.kodejava.example.fundamental;

public enum Rainbow {
    RED("FF0000"),
    ORANGE("FFA500"),
    YELLOW("FFFF00"),
    GREEN("008000"),
    BLUE("0000FF"),
    INDIGO("4B0082"),
    VIOLET("EE82EE");

    private String colorCode;

    // The constructor of Rainbow enum.
    Rainbow(String colorCode) {
        this.colorCode = colorCode;
    }

    /**
     * Get the hex color code.
     * @return
     */
    public String getColorCode() {
        return colorCode;
    }
}
public class EnumConstructor {
    public static void main(String[] args) {

        // To get all values of the Rainbow enum we can call the Rainbow.values()
        // method which return an array of Rainbow enum values.  
        for (Rainbow color : Rainbow.values()) {
            System.out.println("Color = " + color.getColorCode());
        }
    }
}

How do I use enum in switch statement?

This example show you how to use enumeration or enum type in a switch statement.

package org.kodejava.example.fundamental;

enum RainbowColor {
    RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET
}

public class EnumSwitch {
    public static void main(String[] args) {
        RainbowColor color = RainbowColor.INDIGO;

        EnumSwitch es = new EnumSwitch();
        String colorCode = es.getColorCode(color);
        System.out.println("ColorCode = #" + colorCode);
    }

    public String getColorCode(RainbowColor color) {
        String colorCode = "";

        // We use the switch-case statement to get the hex color code of our
        // enum type rainbow colors. We can pass the enum type as expression
        // in the swith. In the case statement we only use the enum named
        // constant excluding its type name.
        switch (color) {
            // We use RED instead of RainbowColor.RED
            case RED:
                colorCode = "FF0000";
                break;
            case ORANGE:
                colorCode = "FFA500";
                break;
            case YELLOW:
                colorCode = "FFFF00";
                break;
            case GREEN:
                colorCode = "008000";
                break;
            case BLUE:
                colorCode = "0000FF";
                break;
            case INDIGO:
                colorCode = "4B0082";
                break;
            case VIOLET:
                colorCode = "EE82EE";
                break;
            default:
                break;
        }
        return colorCode;
    }
}

How do I create enumerations type?

Enumeration is a list of named constants. Every most commonly used programming languages support this feature. But in Java it is officially supported since version 5.0. In Java programming language an enumeration defines a class type. Because an enumeration is a class it can have a constructors, methods, and instance variables.

To create an enumeration we use the enum keyword. For example below is a simple enumeration that hold a list of notebook producers:

package org.kodejava.example.fundamental;

public enum Producer {
    ACER, APPLE, DELL, FUJITSU, LENOVO, TOSHIBA;
}

Below we use our enumeration in a simple program.

package org.kodejava.example.fundamental;

public class EnumDeclaration {
    public static void main(String[] args) {
        // Creating an enum variable declaration and assignment. Because the
        // produced is of type Producer we can only assign value defined by
        // enumeration.
        Producer producer = Producer.APPLE;

        if (producer == Producer.LENOVO) {
            System.out.println("Produced by Lenovo.");
        } else {
            System.out.println("Produced by others.");
        }
    }
}

The ACER, APPLE, DELL, etc identifiers are called enumeration constants. Every named constants have an implicitly assigned public and static access modifiers. Once we have defined the enumeration we can create a variable of that type. Although the enumeration is a class type to create an enumeration variable we don’t use the new keyword. We create an enum just like creating a primitive type of data, as you can see in the example above.