Enum in Java

Enumerations, or enums for short, are a powerful and convenient way to define a set of named constants in Java. They are essentially a special data type that allows a variable to be a set of predefined values, which makes it easier to write and maintain code that uses these values.

Create Enum in Java

To define an enum, we use the enum keyword followed by a list of values enclosed in curly braces. For example:

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

Here, we have defined an enum called Day that contains seven values: SUNDAY, MONDAY, etc. These values are called enum constants.

Enum as a variable

We can use an enum just like any other data type in Java. For example, we can declare a variable of type Day and assign it one of the enum constants:

Day today = Day.MONDAY;

Using enum in switch case

We can also use enums in switch statements, which can make our code more readable and easier to maintain. For example:

switch (today) {
    case SUNDAY:
        System.out.println("Today is Sunday");
        break;
    case MONDAY:
        System.out.println("Today is Monday");
        break;
    // ...
}

Create method and variable in enum

In addition to the constants defined in the enum, we can also define fields and methods inside the enum. For example:

public enum Day {
    SUNDAY("Sunday"), MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY("Saturday");
    
    private String fullName;
    
    private Day(String fullName) {
        this.fullName = fullName;
    }
    
    public String getFullName() {
        return fullName;
    }
}

Here, we have added a field called fullName and a method called getFullName to the Day enum. The fullName field is initialized in the constructor, which is called whenever an enum constant is created. The getFullName method simply returns the value of the fullName field.

Conclusion

Enums are a great tool to use when we have a fixed set of values that a variable can take on. They can make our code more readable and easier to maintain, and they can also help prevent errors by ensuring that only valid values are used.