Java - Enums in Java

An enum (enumeration) in Java is a special data type used to represent a fixed set of named constants. It is useful when a variable can have only a limited number of predefined values.

For example, the days of a week, months of a year, directions, traffic-light colors, order statuses, or user roles can be represented using enums.

Instead of using ordinary strings or integers, enums make the program more readable, safer, and easier to maintain.

1. What Is an Enum?

An enum is declared using the enum keyword.

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

Here, Day is an enum type, and the seven values are its constants.

A variable of type Day can contain only one of these predefined values.

Day today = Day.MONDAY;

This is different from using a string:

String today = "Monday";

With a string, a programmer could accidentally write:

String today = "Mondaay";

There is no compile-time restriction preventing the incorrect value. An enum avoids this type of problem.

2. Why Are Enums Used?

Enums are useful when a program needs a fixed collection of related values.

For example, consider an online order:

enum OrderStatus {
    PENDING,
    CONFIRMED,
    SHIPPED,
    DELIVERED,
    CANCELLED
}

An order can then have a status:

OrderStatus status = OrderStatus.SHIPPED;

The enum makes the possible statuses clear and prevents arbitrary values from being assigned.

Common applications include:

  • Days of the week

  • Months

  • Directions

  • Gender categories where applicable to a fixed domain model

  • Traffic-light states

  • Order statuses

  • Payment statuses

  • User roles

  • Application modes

  • Difficulty levels

  • Menu choices

3. Declaring an Enum

The basic syntax is:

enum EnumName {
    CONSTANT1,
    CONSTANT2,
    CONSTANT3
}

Example:

enum Color {
    RED,
    GREEN,
    BLUE
}

A variable can then be declared using the enum:

Color color = Color.RED;

The enum constant is accessed using the dot operator:

Color.RED
Color.GREEN
Color.BLUE

4. Enum Constants

The values declared inside an enum are called enum constants.

For example:

enum Size {
    SMALL,
    MEDIUM,
    LARGE
}

SMALL, MEDIUM, and LARGE are enum constants.

By convention, enum constants are generally written in uppercase letters.

You can use an enum constant in conditional statements:

Size size = Size.MEDIUM;

if (size == Size.MEDIUM) {
    System.out.println("Medium size selected");
}

5. Enum with a Switch Statement

Enums work particularly well with switch.

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

public class Main {
    public static void main(String[] args) {

        Day day = Day.MONDAY;

        switch (day) {
            case MONDAY:
                System.out.println("Start of the working week");
                break;

            case FRIDAY:
                System.out.println("Last working day");
                break;

            case SATURDAY:
            case SUNDAY:
                System.out.println("Weekend");
                break;

            default:
                System.out.println("Working day");
        }
    }
}

The switch expression compares the enum value with its available constants.

6. Enum and values() Method

Every enum automatically provides a values() method.

It returns an array containing all the constants declared in the enum.

Example:

enum Season {
    SPRING,
    SUMMER,
    AUTUMN,
    WINTER
}

We can access all values using:

for (Season season : Season.values()) {
    System.out.println(season);
}

Output:

SPRING
SUMMER
AUTUMN
WINTER

This is useful when a program needs to process every possible enum value.

7. Enum and valueOf() Method

The valueOf() method converts a string into the corresponding enum constant.

Example:

enum Direction {
    NORTH,
    SOUTH,
    EAST,
    WEST
}

We can write:

Direction direction = Direction.valueOf("NORTH");

System.out.println(direction);

Output:

NORTH

The string must exactly match an enum constant.

For example:

Direction.valueOf("north");

does not match NORTH because enum constant names are case-sensitive.

8. Enum and ordinal() Method

The ordinal() method returns the position of an enum constant.

The first constant has an ordinal value of 0.

Example:

enum Level {
    LOW,
    MEDIUM,
    HIGH
}

Now:

System.out.println(Level.LOW.ordinal());
System.out.println(Level.MEDIUM.ordinal());
System.out.println(Level.HIGH.ordinal());

Output:

0
1
2

It is important not to treat ordinal values as permanent IDs. If the order of constants changes, their ordinal values also change.

9. Enum with Methods

An enum can contain methods just like a class.

For example:

enum Operation {
    ADD,
    SUBTRACT,
    MULTIPLY
}

An enum can be given a method to perform an operation:

enum Operation {
    ADD,
    SUBTRACT,
    MULTIPLY;

    int calculate(int a, int b) {
        switch (this) {
            case ADD:
                return a + b;

            case SUBTRACT:
                return a - b;

            case MULTIPLY:
                return a * b;

            default:
                return 0;
        }
    }
}

The method can be used as follows:

public class Main {
    public static void main(String[] args) {

        int result = Operation.ADD.calculate(10, 5);

        System.out.println(result);
    }
}

Output:

15

This demonstrates that enums are more powerful than simple collections of constants.

10. Enum with Fields

An enum can also have fields.

For example:

enum Planet {
    EARTH(5.97),
    MARS(0.642),
    JUPITER(1898.0);

    private double mass;

    Planet(double mass) {
        this.mass = mass;
    }

    public double getMass() {
        return mass;
    }
}

Here, each enum constant has an associated mass value.

We can access it using:

System.out.println(Planet.EARTH.getMass());

The constructor is called automatically when the enum constants are created.

11. Enum Constructors

Enums can have constructors, but enum constructors cannot normally be called directly using new.

For example:

enum Month {
    JANUARY(31),
    FEBRUARY(28),
    MARCH(31);

    private int days;

    Month(int days) {
        this.days = days;
    }

    public int getDays() {
        return days;
    }
}

Here, the constructor:

Month(int days)

is automatically used for each constant.

For example:

JANUARY(31)

passes 31 to the constructor.

12. Enum Implementing an Interface

An enum can implement an interface.

Example:

interface Printable {
    void print();
}

enum Color implements Printable {
    RED,
    GREEN,
    BLUE;

    public void print() {
        System.out.println("Color: " + this);
    }
}

We can use:

Color.RED.print();

Output:

Color: RED

This shows that enums can participate in Java's object-oriented programming features.

13. Comparing Enum Values

Enum values are commonly compared using the == operator.

Example:

enum Status {
    ACTIVE,
    INACTIVE
}

Status status = Status.ACTIVE;

if (status == Status.ACTIVE) {
    System.out.println("User is active");
}

This is safe because each enum constant represents a specific enum object.

You can also use equals(), but == is generally straightforward and appropriate for enum constants.

14. Enum vs Constants Using Integers

Before enums, programmers often represented fixed choices using integers.

For example:

int RED = 1;
int GREEN = 2;
int BLUE = 3;

Then:

int color = 1;

This approach has disadvantages. The meaning of 1, 2, and 3 is not immediately obvious, and unrelated integer values could accidentally be assigned.

With an enum:

enum Color {
    RED,
    GREEN,
    BLUE
}

Color color = Color.RED;

The code is much easier to understand.

15. Enum vs String Values

Another common approach is using strings:

String status = "SHIPPED";

However, strings allow invalid values:

String status = "SHIPED";

An enum provides stronger type safety:

OrderStatus status = OrderStatus.SHIPPED;

The compiler can detect incompatible assignments.

16. Advantages of Enums

Enums provide several important advantages:

Type safety:
Only predefined constants belonging to the enum can be assigned to an enum variable.

Readability:
OrderStatus.SHIPPED is clearer than an arbitrary value such as 3.

Maintainability:
Related constants are grouped into one meaningful type.

Reduced errors:
Enums prevent many accidental invalid values.

Object-oriented support:
Enums can have fields, constructors, methods, and can implement interfaces.

Useful with switch:
Enums can be used naturally in conditional logic.

17. Complete Example

The following example demonstrates a practical enum:

enum OrderStatus {
    PENDING,
    CONFIRMED,
    SHIPPED,
    DELIVERED,
    CANCELLED
}

public class Main {

    public static void main(String[] args) {

        OrderStatus status = OrderStatus.SHIPPED;

        System.out.println("Current Status: " + status);

        switch (status) {

            case PENDING:
                System.out.println("Order is waiting for confirmation.");
                break;

            case CONFIRMED:
                System.out.println("Order has been confirmed.");
                break;

            case SHIPPED:
                System.out.println("Order has been shipped.");
                break;

            case DELIVERED:
                System.out.println("Order has been delivered.");
                break;

            case CANCELLED:
                System.out.println("Order has been cancelled.");
                break;
        }
    }
}

Output:

Current Status: SHIPPED
Order has been shipped.

18. Important Points to Remember

An enum is a special Java type used to represent a fixed set of constants. It is declared with the enum keyword. Enum constants are normally written in uppercase. An enum variable can store only a value belonging to that enum type. Java automatically provides useful methods such as values(), valueOf(), and ordinal(). Enums can also contain fields, constructors, and methods and can implement interfaces.

Conclusion

Enums in Java provide a clean and type-safe way to represent a fixed set of related values. They are preferable to arbitrary integers or strings when the possible values are known in advance. Although enums begin as a simple list of constants, Java allows them to contain constructors, fields, methods, and interface implementations, making them a powerful feature for designing well-structured applications.