Course contentsShow
← Java
Lesson 582 of 2,87014. EnumerationsFree lesson

The values() Method: Iterating All Constants

Using the compiler-generated values() method to loop through all enum constants in declaration order.

The values() Method: Iterating All Constants

What you'll learn: How to use the compiler-generated values() method to loop through every constant in an enum.

The Built-In values() Method

When you declare an enum, the Java compiler secretly generates several helper methods for you. One of the most useful is values(), which returns an array containing all the enum constants in the exact order they were declared.

Think of values() like asking for a complete guest list at a party—it hands you every attendee in the order they arrived (were declared).

Using values() to Iterate

The values() method has this signature:

public static EnumType[] values()

You call it directly on the enum type itself, and it returns an array you can loop through:

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

public class EnumDemo {
    public static void main(String[] args) {
        Day[] allDays = Day.values();
        
        for (Day d : allDays) {
            System.out.println(d);
        }
    }
}

Output:

MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

The order is guaranteed to match your declaration order. If you declare FRIDAY before MONDAY, that's the order values() will return them.

Why This Matters

The values() method lets you write flexible code that automatically adapts when you add or remove enum constants. You don't need to manually track or list your constants—the compiler does it for you.

Key Takeaway: Every enum automatically has a values() method that returns an array of all constants in declaration order, making it trivial to iterate through all possible values.