Java enum FAQ: Can you share some Java enum for loop examples?
I’ve written several Java enum tutorials recently, (Java enum examples tutorial, Java enum switch example, and Java enum toString tutorial), and before leaving the “Java enum” topic, I thought it would be good to show one example that just focuses on the Java enum for loop syntax.
Java enum for loop example
To that end, here’s the source code for a complete Java enum class that demonstrates how to iterate over the values in a Java enum using the Java 5 for loop syntax:
/** * A Java enum for loop example. * @author alvin alexander, alvinalexander.com */ public class JavaEnumForLoopExample { public static void main(String[] args) { // loop through a java enum with a java5 for loop for (Day d: Day.values()) { System.out.println(d); } } } enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
Java enum for loop discussion
As you can see in the example, the Java enum for
loop code looks like this:
for (Day d: Day.values()) { System.out.println(d); }
This is a standard Java 5 for
loop, with the only here being the use of the values
method of our Java enum. This values
method returns an enum array -- in this case an enum array of type Day
(Day[]
) -- that our Java 5 for
loop can iterate through.
As you might guess from looking at the code -- and knowing that the values
method returns an enum array -- the output from the test enum class is:
SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY
Java enum for loop example - What's Related
As I finish up my Java enum series, including this Java enum for loop example, here’s a collection of the Java enum tutorials I’ve put together during the last week. I hope you find them helpful: