Module 26 of 30 · Java Programming — Core to Enterprise · Intermediate

Java Enums

Duration: 7 min

Enums (enumerations) are a special data type in Java that allow you to define a set of constants. They are useful for representing a fixed set of related values, such as days of the week, directions, or states. Enums provide type safety and make code more readable and maintainable.

Enum Declaration and Constants

An enum is declared using the enum keyword. Each constant in an enum is an instance of that enum type.

public enum DayOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class EnumUsage {
    public static void main(String[] args) {
        DayOfWeek day = DayOfWeek.MONDAY;
        System.out.println("Today is: " + day);
        System.out.println("Ordinal: " + day.ordinal());
    }
}
Today is: MONDAY
Ordinal: 0

Enums with Methods and Constructors

Enums can have constructors, fields, and methods just like regular classes. This allows you to associate data with each constant.

public enum Season {
    SPRING(20, "Warm"),
    SUMMER(30, "Hot"),
    FALL(15, "Cool"),
    WINTER(5, "Cold");
    
    private int temperature;
    private String description;
    
    Season(int temperature, String description) {
        this.temperature = temperature;
        this.description = description;
    }
    
    public int getTemperature() {
        return temperature;
    }
    
    public String getDescription() {
        return description;
    }
}
public class SeasonTest {
    public static void main(String[] args) {
        Season s = Season.SUMMER;
        System.out.println(s + ": " + s.getDescription() + " (" + s.getTemperature() + "°C)");
    }
}
SUMMER: Hot (30°C)

EnumSet and EnumMap

EnumSet and EnumMap are specialized collections optimized for enums. They are more efficient than regular sets and maps when working with enum constants.

import java.util.*;

public class EnumCollections {
    public static void main(String[] args) {
        // EnumSet example
        EnumSet<DayOfWeek> weekdays = EnumSet.of(
            DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY,
            DayOfWeek.THURSDAY, DayOfWeek.FRIDAY
        );
        System.out.println("Weekdays: " + weekdays);
        
        // EnumMap example
        EnumMap<Season, String> activities = new EnumMap<>(Season.class);
        activities.put(Season.SPRING, "Gardening");
        activities.put(Season.SUMMER, "Swimming");
        activities.put(Season.FALL, "Hiking");
        activities.put(Season.WINTER, "Skiing");
        
        for (Season s : Season.values()) {
            System.out.println(s + ": " + activities.get(s));
        }
    }
}
Weekdays: [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY]
SPRING: Gardening
SUMMER: Swimming
FALL: Hiking
WINTER: Skiing

Enums with Abstract Methods

Enums can declare abstract methods that must be implemented by each constant. This is useful for defining different behaviors for each enum value.

public enum Operation {
    ADD("+") {
        public double apply(double x, double y) { return x + y; }
    },
    SUBTRACT("-") {
        public double apply(double x, double y) { return x - y; }
    },
    MULTIPLY("*") {
        public double apply(double x, double y) { return x * y; }
    },
    DIVIDE("/") {
        public double apply(double x, double y) { return x / y; }
    };
    
    private String symbol;
    
    Operation(String symbol) {
        this.symbol = symbol;
    }
    
    public abstract double apply(double x, double y);
    
    public String getSymbol() {
        return symbol;
    }
}
public class Calculator {
    public static void main(String[] args) {
        double x = 10, y = 5;
        for (Operation op : Operation.values()) {
            System.out.println(x + " " + op.getSymbol() + " " + y + " = " + op.apply(x, y));
        }
    }
}
10.0 + 5.0 = 15.0
10.0 - 5.0 = 5.0
10.0 * 5.0 = 50.0
10.0 / 5.0 = 2.0

Real-World Patterns: State Machines

Enums are excellent for implementing state machines. Each enum constant represents a state, and methods define transitions.

public enum OrderStatus {
    PENDING("Order received"),
    PROCESSING("Processing order"),
    SHIPPED("Order shipped"),
    DELIVERED("Order delivered"),
    CANCELLED("Order cancelled");
    
    private String description;
    
    OrderStatus(String description) {
        this.description = description;
    }
    
    public OrderStatus nextStatus() {
        switch(this) {
            case PENDING: return PROCESSING;
            case PROCESSING: return SHIPPED;
            case SHIPPED: return DELIVERED;
            default: return this;
        }
    }
    
    public String getDescription() {
        return description;
    }
}

❓ What is the output of the following code?

DayOfWeek day = DayOfWeek.FRIDAY;
System.out.println(day.ordinal());









❓ Which collection is optimized for storing enum constants?

❓ Can an enum have a constructor?

❓ What does the values() method return for an enum?

❓ Which pattern uses enums to represent different states and transitions?

Learn more: https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

← Previous Continue interactively → Next →

Related Courses