Enumeration in Java

Enumeration in Java allows you to define a set of named values, which can be used as constants in your code. It provides a convenient way to represent a group of related values and enhances the readability and maintainability of your programs.

Declaring an Enumeration

To declare an enumeration in Java, you use the enum keyword followed by the name of the enumeration type. Inside the curly braces, you list the constants of the enumeration, separated by commas.

Syntax
enum EnumerationName {
    CONSTANT1,
    CONSTANT2,
    // Additional constants
}
Example
enum DayOfWeek {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}
Accessing Enumeration Constants

To access the constants of an enumeration, you use the dot notation, specifying the enumeration name followed by the constant name.

Example
DayOfWeek today = DayOfWeek.MONDAY;
System.out.println("Today is: " + today);
Using Enumeration in a Switch Statement

Enumerations are commonly used in switch statements to handle different cases based on the enumeration constant.

Example
DayOfWeek day = DayOfWeek.FRIDAY;
switch (day) {
    case MONDAY:
        System.out.println("It's Monday. Start of the week.");
        break;
    case FRIDAY:
        System.out.println("It's Friday. Weekend is coming!");
        break;
    // Handle other cases
}

Adding Methods and Fields to an Enumeration

You can add methods and fields to an enumeration, allowing you to perform custom operations or associate additional data with the enumeration constants.

Syntax
enum EnumerationName {
    CONSTANT1,
    CONSTANT2,
    // Additional constants

    // Methods and fields
    returnType methodName() {
        // Method implementation
    }

    dataType fieldName;
}
Example
enum TrafficLight {
    RED("Stop"),
    YELLOW("Caution"),
    GREEN("Go");

    private String message;

    TrafficLight(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}
Note

Enumeration in Java provides a powerful way to define a fixed set of named values. It improves the clarity and maintainability of your code by representing related constants as a group. By understanding the syntax and usage of enumerations, you can leverage this feature to enhance the structure and readability of your Java programs.