Home » Enum class in Java

Enum class in Java

Enum class in Java

Introduction

Enum, introduced in Java 5, is a special data type that consists of a set of pre-defined named values separated by commas. These named values are also known as elements enumerators or enum instances. Since the values in the enum type are constant, you should always represent them in UPPERCASE letters. it cannot inherit other classes but can implement multiple interfaces. We can also have methods, constructors, etc inside enum class in Java.

You can use an Enum type when you need a fixed set of pre-defined constant values that are known at the compile-time itself. Examples can be days of the week, seasons of the year, etc.

Declaration of Enum in Java

Enums can be declared inside or outside a class.

Note: – Enums cannot be declared inside a method.

Syntax

enum-declearation.png

Example 1-

public enum TypeName {
    CONSTANT1,
    CONSTANT2,
    CONSTANT3,
    // add more constants as needed
}
Java

Example 2 –

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

Declaring Enum Class Inside the Class

In Java, you can declare an enum inside a class. This is useful when the enum is tightly coupled with the functionality of that particular class and doesn’t need to be used outside of it

Example

public class MyClass {
    // Other fields and methods can go here

    public enum InnerEnum {
        VALUE1,
        VALUE2,
        VALUE3
    }

    // Other fields and methods can go here
}
Java

InnerEnum is an enum declared inside the MyClass class. It follows the same syntax as declaring a regular enum, but it’s scoped within MyClass. Here’s an example of how you can use the inner enum

public class EnumInsideClassExample {
    public static void main(String[] args) {
        MyClass.InnerEnum enumValue = MyClass.InnerEnum.VALUE1;
        System.out.println("Enum value: " + enumValue);
    }
}
Java

In this example, MyClass.InnerEnum is used to refer to the enum InnerEnum declared inside MyClass.

Declaring enums inside classes is a good practice when the enum is closely related to the class and is not meant to be used outside of it. It helps encapsulate the enum’s scope and reduces clutter in the namespace.

Enum in a Switch Statement

Example

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

    public static void main(String[] args) {
        Day today = Day.MONDAY;

        switch (today) {
            case SUNDAY:
                System.out.println("Today is Sunday");
                break;
            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;
            default:
                System.out.println("Unknown day");
                break;
        }
    }
}
Java

In this example, we have an enum Day representing the days of the week. We then declare a variable today of type Day and initialize it to Day.MONDAY. We use a switch statement to print out a message depending on the value of today. The default case handles any unexpected values.

When you run this code with Day.MONDAY as the value of today, it will print:

Output

Today is Monday
Java

This demonstrates how enums can be used effectively with switch statements to make your code more readable and maintainable.

Loop Through an Enum

Example

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

    public static void main(String[] args) {
        // Loop through the enum values
        for (Day day : Day.values()) {
            System.out.println(day);
        }
    }
}
Java

In this example, we have an enum Day representing the days of the week. We use the values() method provided by enums in Java, which returns an array containing all of the enum constants in the order they are declared. We then loop through this array using an enhanced for loop (also known as a for each loop) and print out each enum constant.

Output

SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
Java

This demonstrates how you can easily loop through an enum in Java using the values() method.

Properties of Enum in Java

Here are the properties of enum class in java presented in bullet points:

  • Enums are special data types used to define collections of constants.
  • Enum constants are static and final by default.
  • Enums can have constructors, fields, and methods like regular classes.
  • Enums can implement interfaces, enabling them to have behaviors.
  • Enums are implicitly serializable and deserializable.
  • Enums can be compared using == for reference comparison and equals() for value comparison.
  • Enums can be used in switch statements for easy code readability.
  • Enums can be iterated over using the values() method, which returns an array of enum constants.
  • Enums provide type safety, preventing invalid values from being assigned.
  • Enums enhance code clarity by grouping related constants together.
  • Enums are used to represent a fixed set of values that are not expected to change at runtime.

These properties make enums a powerful tool in Java for representing fixed sets of constants clearly and concisely.

Conclusion

Enum class in java are a powerful feature that allows developers to define a set of named constants within a single type. They offer several advantages, including improved type safety, enhanced code readability, and better maintainability. Enums can have constructors, fields, and methods, making them versatile for various programming tasks. They support interfaces, enabling polymorphic behavior, and can be easily serialized and deserialized. Additionally, enums are commonly used in switch statements and iteration loops, simplifying code implementation and improving clarity. Overall, Java enums provide an elegant and efficient way to represent fixed sets of related constants, making them an essential component of Java programming.

Frequently Asked Questions

What is a Java enum?

A Java enum, short for enumeration, is a special data type that defines a set of constants. Enums in Java provide a way to create predefined instances of a class representing a fixed number of options or states.

How do you declare an enum in Java?

To declare an enum in Java, you use the enum keyword followed by the name of the enum type and the list of constants within curly braces.

Can enums have methods in Java?

Yes, enums in Java can have methods. You can add methods, fields, and constructors to enums just like you would with regular classes. Each enum constant is actually an instance of the enum type, so you can call methods on them.

How do you access enum constants in Java?

Enum constants in Java can be accessed using dot notation.
For example:
Day today = Day.MONDAY;

Can enums implement interfaces in Java?

Yes, enums in Java can implement interfaces. This allows enums to provide specific implementations for methods defined in interfaces.