Course Content
Core Java
About Lesson

An enum, short for enumeration, is a special data type (class) used to define a fixed set of named constants (unchangeable variables like final variables). They provide a way to define a collection of related constants in a more structured and type-safe manner.

Enums are declared using the enum keyword in Java

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

Enum constants defined within enum declaration are implicitly public , static and final

Enums can be defined in separate source files in Java. Just like classes, enums can have their own source files.

Allowed Access Modifiers in Enum

  1. Public : When an enum is declared as public, it can be accessed from any other class or package.
public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
  1. Default (no modifier) : If no access modifier is specified, the enum is accessible within the same package.
enum Month {
    JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY,
    AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
}

Enums are implicitly final and static, so they cannot be declared with those modifiers explicitly.

Constants in Enum

Each enum constant is implicitly public, static, and final. This means that enum constants are accessible from any class, can be referenced without creating an instance of the enum, and cannot be reassigned after initialization. You cannot explicitly specify access modifiers for individual enum constants inside the enum definition.

When you print an enum constant in Java, it will print the name of the enum constant itself.

Each enum constant can have its own implementation of the methods and access fields defined within the enum.

Constructor in Enum

Enumerations (enums) can have constructors, allowing you to provide custom initialization logic for each enum constant.

public enum Month {
    JANUARY(1, "January", 31),
    FEBRUARY(2, "February", 28),
    MARCH(3, "March", 31),
    APRIL(4, "April", 30),
    MAY(5, "May", 31),
    JUNE(6, "June", 30),
    JULY(7, "July", 31),
    AUGUST(8, "August", 31),
    SEPTEMBER(9, "September", 30),
    OCTOBER(10, "October", 31),
    NOVEMBER(11, "November", 30),
    DECEMBER(12, "December", 31);

    private final int monthNumber;
    private final String monthName;
    private final int daysInMonth;

    // Constructor
    private Month(int monthNumber, String monthName, int daysInMonth) {
        this.monthNumber = monthNumber;
        this.monthName = monthName;
        this.daysInMonth = daysInMonth;
    }

    // Getter methods
    public int getMonthNumber() {
        return monthNumber;
    }

    public String getMonthName() {
        return monthName;
    }

    public int getDaysInMonth() {
        return daysInMonth;
    }
}

Each enum constant (SUNDAY, MONDAY, etc.) can have its own initialization parameters. The enum constructor is declared as private to prevent outside classes from creating new instances of the enum. It takes parameters corresponding to the initialization values of each enum constant. When the enum constants are defined (SUNDAY("First day of the week"), etc.), the constructor is invoked with the specified arguments. Enums can have fields (eg monthNumber) to store additional information associated with each enum constant. A getter method (getMonthNumber()) is provided to retrieve the description associated with each enum constant.

public class MonthExample {
    public static void main(String[] args) {
        Month month = Month.JANUARY;
        System.out.println("Month: " + month.getMonthName());
        System.out.println("Number of days: " + month.getDaysInMonth());
    }
}

Enum in a Switch Statement

Enums provide a type-safe way to represent a fixed set of constants, and switch-case statements allow you to execute different blocks of code based on the value of an enum variable.

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumSwitchExample {
    public static void main(String[] args) {
        Day today = Day.MONDAY;

        switch (today) {
            case MONDAY:
                System.out.println("Today is Monday.");
                break;
            case TUESDAY:
                System.out.println("Today is Tuesday.");
                break;
            case WEDNESDAY:
                System.out.println("Today is Wednesday.");
                break;
            case THURSDAY:
                System.out.println("Today is Thursday.");
                break;
            case FRIDAY:
                System.out.println("Today is Friday.");
                break;
            case SATURDAY:
                System.out.println("Today is Saturday.");
                break;
            case SUNDAY:
                System.out.println("Today is Sunday.");
                break;
            default:
                System.out.println("Invalid day.");
        }
    }
}

We define an enum variable today and initialize it with Day.MONDAY. We use a switch-case statement to check the value of today. Each case corresponds to a different enum constant (MONDAY, TUESDAY, etc.) Depending on the value of today, the corresponding case block is executed.

Loop through an Enum

Looping through an enum in Java allows you to iterate over all the enum constants and perform operations on them.

public class EnumLoopExample {
    public static void main(String[] args) {
        // Method 1 Using for-each loop
        for (Day day : Day.values()) {
            System.out.println(day);
        }
        
        // Method 2 using for loop with ordinal value
        for (int i = 0; i < Day.values().length; i++) {
            System.out.println(Day.values()[i]);
        }
        
        // Method 3 Using streams and forEach() method 
        Arrays.stream(Day.values()).forEach(System.out::println);
    }
}

Enum inside Class

Enums can be declared inside the class.

public class Car {
    // Enum to represent different types of cars
    public enum CarType {
        SEDAN, COUPE, HATCHBACK, SUV, CONVERTIBLE, MINIVAN, TRUCK
    }

    private String brand;
    private String model;
    private CarType type;

    // Constructor
    public Car(String brand, String model, CarType type) {
        this.brand = brand;
        this.model = model;
        this.type = type;
    }

    // Getters
    public String getBrand() {
        return brand;
    }

    public String getModel() {
        return model;
    }

    public CarType getType() {
        return type;
    }

    // Setters
    public void setBrand(String brand) {
        this.brand = brand;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public void setType(CarType type) {
        this.type = type;
    }

    // toString method for printing car details
    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", model='" + model + '\'' +
                ", type=" + type +
                '}';
    }
}
public class Main {
    public static void main(String[] args) {
        // Create Car objects with different CarTypes
        Car car1 = new Car("Toyota", "Camry", Car.CarType.SEDAN);
        Car car2 = new Car("Ford", "Mustang", Car.CarType.COUPE);
        Car car3 = new Car("Honda", "Civic", Car.CarType.HATCHBACK);

        // Print car details
        System.out.println(car1);
        System.out.println(car2);
        System.out.println(car3);

        // Change the type of a car
        car1.setType(Car.CarType.SUV);
        System.out.println("Updated car1: " + car1);
    }
}

Scroll to Top