Enum in Java

Enumerations, or enums for short, are a powerful and convenient way to define a set of named constants in Java. Enum in Java are essentially a special data type that allows a variable to be a set of predefined values. This makes easier to write and maintain code that uses these values. In this post, we will learn what is enum type in Java with example.

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.

FAQs about Enum in Java

Can enums have methods?

Yes, enums can have constructors, instance variables, and methods just like regular classes.

Are enums part of the Java Collections Framework?

No, enums are not part of the Java Collections Framework. They are a separate type of data structure.

Can I compare enums?

Yes, enums can be compared using the == operator or the equals() method.

Can I use enums as keys in HashMaps?

Yes, enums can be used as keys in HashMaps and other data structures.

Can I add new enum constants at runtime?

No, enums are defined at compile-time and cannot be modified or extended at runtime.

Are enums type-safe?

Yes, enums provide type safety, as they restrict the possible values to the ones defined in the enum.