Java

Enum in Java | Explained

Java provides an enum class that can be used to represent a group of constants and it can have class attributes, member functions, and constructors. Enum class can’t inherit some other class but it can implement different interfaces and we can’t create the object of the enum class.

In java, if we have to specify a single value as constant we can use the final keyword. However if we have to specify a group/set of constants then we can utilize the concept of enums. In java, numerous methods are available that can be used to perform various functionalities like values(), ordinal(), and many more.

This article presents a profound understanding of the following concepts regarding Java Enums:

  • What is Enum in Java
  • Basic Syntax
  • How to use Enum in a Class
  • How to Iterate Through Enum
  • How to use Enum in Switch Statement

So let’s get started!

Enum in Java

Enum acronym of enumerations is a special class that consists of a group of constants (whose values can’t be changed) and will be written in uppercase letters. So, enums are widely used when we have surety that values are not going to be changed such as the name of months, color names, etc.

Basic Syntax

In java, enum class can be created with the help of enum keyword as shown in the below-given syntax:

enum Example {

//set of constants written in Uppercase

}

As enum contains a set of constants and according to Java naming convention a “constant” must be in uppercase, therefore, all the values within enum will be written in Capital letters.

How to Create and Access an Enum in Java

The enums can be created with the help of enum keyword and as enum contains a group of constants so, all these constants will be separated with a comma (,) as described in the below-given snippet:

enum Example {

FRIDAY,

SATURDAY,

SUNDAY

}

An enum constant can be accessed with the dot(.) syntax as demonstrated in the below snippet:

Example exp = exp.SUNDAY

Enum in Classes

In java, we can utilize the enum within a class to represent a group of constants.

Example

In this example we will use an enum in a class and within the enum, we specify some values.

public class EnumsExample {
  enum WeekDays{
      SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
  }
  public static void main(String[] args) {
      WeekDays dayObj = WeekDays.FRIDAY;
      System.out.println(day);
}

We access the values of enum from the main method. The complete code with the respective output is provided in the below-given screenshot:

The above snippet shows how to create enum within the class, and the output verifies the effectiveness of the enum.

How to Iterate Through Enum

In java, enums can be used to traverse all the values of constants and to do so, we can use the values() method to get an array that contains all the values of the enum.

Example

In this example, we will create an enum within a class that contains the names of weekdays and with the help of the values() method, we will try to traverse all the values of enum:

public class EnumsExample {
    enum WeekDays{
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    }
    public static void main(String[] args) {
        for (WeekDays day : WeekDays.values())
            System.out.println(day);
    }  
}

The below-given snippet describes the working of values() method:

The output authenticates the working of values() method as it returns the complete array of Constants.

Finding index of an enum constant

The combination of valueOf() and ordinal() methods will be utilized in order to find the index of an enum constant. In the valueOf() method we have to mention the value whose index we want to find out.

Example

The below snippet explains how to find the index of an enum constant:

ystem.out.println("Index of Friday: " + WeekDays.valueOf("FRIDAY").ordinal());

The above piece of code generates the following output:

The output validates the working of ordinal() method as it returns the proper index of the specified value.

Enum in Switch Statement

We can also utilize the enums in switches to test the corresponding values.

Example

The below-given snippet has an enum that contains names of the week days. In the main method we create seven switch cases for each weekday, and we specified a condition to find the WEDNESDAY.

public class EnumsExample {
   
 enum WeekDays {
        SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
    }
    public static void main(String[] args) {
        WeekDays day = WeekDays.WEDNESDAY;
        switch (day) {
            case MONDAY:
                System.out.println("MONDAY");
                break;
            case TUESDAY:
                System.out.println("TUESDAY");
                break;
            case WEDNESDAY:
                System.out.println("WEDNESDAY");
                break;
            case THURSDAY:
                System.out.println("THURSDAY");
                break;
            case FRIDAY:
                System.out.println("FRIDAY");
                break;
            case SATURDAY:
                System.out.println("SATURDAY");
                break;
            case SUNDAY:
                System.out.println("SUNDAY");
                break;
        }
    }
}

Following will be the output for the above code snippet:

The output verifies that enum works appropriately within the Java switch statement.

Conclusion

In java, enum is a special class that contains a group of constants and can be used when there is guarantee that the certain values are not going to be changed throughout the program. Enum provide some predefined methods such as values() that returns array of enum constants, ordinal() returns index of enum constants, and many more methods that can be used to perform different functionalities.

This write-up provide a detailed overview of what is an enum, and how to use enum in java classes and switch statements.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.