Enums in Java

Fri, Aug 11, 2023 2-minute read

Enumerations (enums) in Java are a special type of class that can have a set of constant values. This means that once an enum has been defined, the values in it cannot be modified. Enums are useful for representing fixed sets of related constants, such as days of the week, months of the year, or directions (NORTH, SOUTH, EAST, WEST).

Basics of Enum

Here’s a basic example to define an enum for days of the week:

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

In this example, Day is an enum with seven constants: SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY.

How to Use Enum

Declaring a Variable

You can declare a variable of an enum type just like you would for any other data type:

Day today;

Assigning a Value

You can assign a value to an enum variable using the enum constants:

today = Day.MONDAY;

Using in Switch Statements

Enums are often used in switch statements:

switch (today) {
    case MONDAY:
        System.out.println("Start of the work week.");
        break;
    case FRIDAY:
        System.out.println("End of the work week.");
        break;
    default:
        System.out.println("It's a regular day.");
        break;
}

Iterating Through Enum Values

You can also loop through all enum values using the values() method:

for (Day d : Day.values()) {
    System.out.println(d);
}

Advanced Features

Adding Methods and Fields

Enums can have methods, constructors, and instance variables. Here’s an example:

public enum Day {
    SUNDAY("Rest day"),
    MONDAY("Work day"),
    // ... others
    SATURDAY("Weekend");

    private final String description;

    Day(String description) {
        this.description = description;
    }

    public String getDescription() {
        return description;
    }
}

In this example, each Day has a description. You can access it by calling the getDescription() method:

System.out.println(Day.MONDAY.getDescription());  // Output: "Work day"

Enum in Collections and Maps

You can also use enums as keys in maps or elements in sets and lists.

Map<Day, String> dayActivityMap = new HashMap<>();
dayActivityMap.put(Day.MONDAY, "Work");
dayActivityMap.put(Day.SUNDAY, "Rest");

When to Use Enum

  • When you have a fixed set of related constants.
  • When you want to use the enum type in switch statements.
  • When you want to ensure type safety.

By using enums, you make the code more readable and maintainable.