How to Iterate Over Enum in Java: Simple Guide
In Java, you can iterate over an enum using the
values() method, which returns an array of all enum constants. Use a for-each loop to go through each enum value easily.Syntax
To iterate over an enum, use the values() method that returns all enum constants as an array. Then, use a for-each loop to access each constant.
EnumType.values(): returns an array of enum constants.for (EnumType item : EnumType.values()): loops through each enum constant.
java
for (EnumType item : EnumType.values()) { // use item }
Example
This example shows how to define an enum Day and iterate over all its values to print each day.
java
public class EnumIterationExample { enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } public static void main(String[] args) { for (Day day : Day.values()) { System.out.println(day); } } }
Output
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
Common Pitfalls
One common mistake is trying to iterate over enum values without using values(). Another is modifying enum constants inside the loop, which is not allowed.
Also, avoid using ordinal() for logic because it can break if enum order changes.
java
/* Wrong way: Trying to iterate without values() */ // for (Day day : Day) { // This causes a compile error // System.out.println(day); // } /* Right way: Use values() method */ for (Day day : Day.values()) { System.out.println(day); }
Output
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
Quick Reference
Remember these key points when iterating enums:
- Use
EnumType.values()to get all constants. - Use
for-eachloop for clean iteration. - Do not modify enum constants during iteration.
- Avoid relying on
ordinal()for logic.
Key Takeaways
Use the values() method to get all enum constants as an array.
Iterate enums cleanly with a for-each loop over values().
Never try to iterate enums without calling values(), it causes errors.
Avoid changing enum constants or using ordinal() for logic.
Enums provide a fixed set of constants ideal for safe iteration.