Write a Java Program to Iterate over enum

Java provides an efficient and simple way to define a set of constant values using enums.

Enum types are used to represent fixed sets of constants, and they are commonly used in Java programs to define things such as days of the week, months of the year, and other constant values.

In this tutorial, we will discuss how to iterate over enums in Java.


Iterating over an enum is useful when you need to perform an operation on each value of the enum.

For example, if you have an enum of days of the week and you want to print the name of each day.

To iterate over an enum, you can use the values() method.

This method returns an array of all the enum constants in the order they are declared.

Here is an example of how to use this method to iterate over an enum:

enum DaysOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

public class EnumIterationExample {
    public static void main(String[] args) {
        for (DaysOfWeek day : DaysOfWeek.values()) {
            System.out.println(day);
        }
    }
}

In this example, we define an enum called DaysOfWeek with seven values representing the days of the week.

We then use a for-each loop to iterate over the values of the enum and print the name of each day.

The output of this program will be:

MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

As you can see, the values() method returns an array of all the enum constants in the order they are declared, and we use a for-each loop to iterate over this array.


In conclusion, iterating over enums in Java is a simple and efficient way to perform an operation on each value of the enum.

To iterate over an enum, you can use the values() method, which returns an array of all the enum constants in the order they are declared.