Java Program to Iterate Over Enum Values

In this tutorial, we will learn about how to create an enum and iterate over its values in Java. Enums are a powerful feature in Java that can help you write safer and more readable code by limiting the possible values that a variable can take.

Enumerations, or enums, are a special data type in Java that allow you to define a set of named constants. Enums are typically used when a variable can only take one out of a small set of possible values.

Here is an example of how to create an enum in Java.

public enum Size {
    SMALL("S"), MEDIUM("M"), LARGE("L"), 
    EXTRA_LARGE("XL");

    private String abbreviation;

    private Size(String abbreviation) {
        this.abbreviation = abbreviation;
    }

    public String getAbbreviation() {
        return abbreviation;
    }
}

In this example, we have defined an enum called Size that has four possible values: SMALL, MEDIUM, LARGE, and EXTRA_LARGE. Each value has an associated abbreviation, which is passed to the constructor of the enum.

To iterate over the values of an enum, you can use a for loop or an enhanced for loop (also known as a "foreach" loop). Here's an example of how to use a for loop to iterate over the values of the Size enum.

for (Size size : Size.values()) {
    System.out.println(size + " " + size.getAbbreviation());
}

This will give the following output.

SMALL S
MEDIUM M
LARGE L
EXTRA_LARGE XL

You can also use the traditional for loop like this

for (int i = 0; i < Size.values().length; i++) {
    System.out.println(Size.values()[i] + " " +
        Size.values()[i].getAbbreviation());
}

In this example, we first call the values() method on the Size enum to get an array of all the values. Then we use a for loop to iterate over the array, printing out the name and abbreviation of each value.

Note that enum values are final and cannot be modified, so you cannot add new value or remove any value from enum.

Java Program to Iterate Over Enum Values

enum Weekdays {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, 
    FRIDAY, SATURDAY, SUNDAY
}

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

This program defines an enumeration called "Weekdays" that consists of the seven days of the week. The main method uses a for-each loop to iterate over the values of the enumeration. The values() method returns an array of the enumeration's values in the order they were declared. The loop variable day takes on each value in turn, and the body of the loop prints it out.