Enums

Enums, short for Enumerations, were introduced in Java 5. They are a special data type used to define collections of constants. Enums are used when a variable can only take one of a predefined set of values. Enums enhance code readability, prevent invalid values, and provide type safety.

Declaration and Usage of Enums:

Declaration:

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

Usage:

public class EnumExample {

    public static void main(String[] args) {
        DaysOfWeek today = DaysOfWeek.TUESDAY;

        if (today == DaysOfWeek.TUESDAY) {
            System.out.println("It's Tuesday!");
        }

        // Enum in a switch statement
        switch (today) {
            case MONDAY:
                System.out.println("It's Monday!");
                break;
            case TUESDAY:
                System.out.println("It's Tuesday!");
                break;
            // ... other cases ...
            default:
                System.out.println("It's some other day.");
        }

        // Iterating through enum values
        System.out.println("Days of the week:");
        for (DaysOfWeek day : DaysOfWeek.values()) {
            System.out.println(day);
        }
    }
}

Explanation:

  1. Enum Declaration: Enums are declared using the enum keyword. Enum constants are defined in uppercase letters by convention.

  2. Enum Instantiation: Enum constants can be used like any other objects and assigned to variables. For example, DaysOfWeek today = DaysOfWeek.TUESDAY; assigns the TUESDAY constant to the today variable.

  3. Comparisons: Enums are compared using the == operator. You can use enums in if statements and other conditional constructs.

  4. Switch Statements: Enums work well with switch statements, providing a clean and readable way to handle different cases.

  5. Iterating through Enums: The values() method provides an array of all enum constants, allowing you to iterate through them.

Enums can also have constructors, methods, and fields like regular Java classes. Each enum constant can have its own implementations of methods, allowing enums to have unique behaviors for each constant. Enums are powerful tools for modeling sets of related constants in a clear and type-safe manner.

Last updated