Question
Given this Java enum representing cardinal and intermediate directions:
public enum Direction {
NORTH,
NORTHEAST,
EAST,
SOUTHEAST,
SOUTH,
SOUTHWEST,
WEST,
NORTHWEST
}
How can you write a for loop that iterates over each Direction enum constant?
Short Answer
By the end of this page, you will know how Java enums expose their declared constants through the generated values() method and how to loop through them safely using an enhanced for loop. You will also see indexed loops, real-project patterns, and common pitfalls.
Concept
An enum (short for enumeration) defines a fixed set of named constants. In this example, Direction represents the only directions your program accepts.
Java automatically provides a static values() method for every enum. Calling it returns an array containing all enum constants in the exact order in which they were declared.
Direction[] directions = Direction.values();
Because values() returns an array, you can iterate over it with a loop. The enhanced for loop is usually the clearest option:
for (Direction direction : Direction.values()) {
System.out.println(direction);
}
Enums matter because they replace error-prone strings or arbitrary numbers with a type-safe list of valid choices. A method that accepts Direction cannot accidentally receive values such as "UPWARD" unless that constant exists in the enum.
Mental Model
Think of an enum as a printed list of allowed menu options. Direction is a menu containing eight direction cards.
Direction.values() takes all cards from that menu and gives you an array containing them. The enhanced for loop picks up one card at a time, names it direction, and lets you perform work with it before moving to the next card.
The declaration order is the menu order: NORTH is visited before NORTHEAST, and NORTHWEST is visited last.
Syntax and Examples
The standard syntax is:
for (EnumType item : EnumType.values()) {
// use item
}
For the Direction enum:
for (Direction direction : Direction.values()) {
System.out.println(direction);
}
Output:
NORTH
NORTHEAST
EAST
SOUTHEAST
SOUTH
SOUTHWEST
WEST
NORTHWEST
Each loop iteration assigns one enum constant to direction. By default, printing an enum uses its constant name.
You can also use each value in a switch expression or statement:
for (Direction direction : Direction.values()) {
switch (direction) {
case NORTH, SOUTH -> System.out.println(direction + " is vertical.");
case EAST, WEST -> System.out.println(direction + " is horizontal.");
default -> System.out.println(direction + " is diagonal.");
}
}
If you need the numeric position as well, use an indexed loop:
Direction[] directions = Direction.values();
( ; index < directions.length; index++) {
System.out.println(index + + directions[index]);
}
Step by Step Execution
Consider this code:
for (Direction direction : Direction.values()) {
System.out.println("Moving " + direction);
}
Execution happens as follows:
-
Direction.values()creates an array containing all declared constants:[NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST] -
The loop assigns the first array element,
NORTH, todirection.Moving NORTH -
It assigns
NORTHEASTtodirectionand prints it.Moving NORTHEAST -
The loop continues once for every remaining constant.
-
After
NORTHWESTis processed, there are no more elements, so the loop ends.
The loop does not need you to manage an array index because the enhanced for loop handles traversal automatically.
Real World Use Cases
Iterating over enum values is useful whenever an application must perform the same operation for every allowed state or category.
- Game movement: Try each possible
Directionwhen finding legal moves around a board position. - Settings screens: Render one option for each theme, permission level, language, or notification type.
- Reports: Create a summary row for each order status, payment state, or support priority.
- Validation: Check that configuration provides a label, color, or handler for every enum constant.
- API mapping: Build lookup data for each supported request type or response category.
- Scheduling: Iterate over days of the week to create recurring jobs.
For example, a grid-based game can inspect neighboring cells:
for (Direction direction : Direction.values()) {
System.out.println("Check neighbor in direction: " + direction);
}
Real Codebase Usage
In production code, enums are commonly used with loops to make behavior complete and explicit.
Populate a map for every enum constant
EnumMap is a map designed for enum keys. It is often clearer and more efficient than a general-purpose HashMap when keys are enum values.
import java.util.EnumMap;
import java.util.Map;
Map<Direction, Integer> movementCost = new EnumMap<>(Direction.class);
for (Direction direction : Direction.values()) {
movementCost.put(direction, 1);
}
Validate a mapping is complete
for (Direction direction : Direction.values()) {
if (!movementCost.containsKey(direction)) {
throw new IllegalStateException("Missing cost for " + direction);
}
}
Use enum data instead of repeated conditionals
An enum can contain fields and methods. This keeps information close to each constant.
public enum Direction {
NORTH(0, -1),
NORTHEAST(1, -1),
EAST(, ),
SOUTHEAST(, ),
SOUTH(, ),
SOUTHWEST(-, ),
WEST(-, ),
NORTHWEST(-, -);
deltaX;
deltaY;
Direction( deltaX, deltaY) {
.deltaX = deltaX;
.deltaY = deltaY;
}
{
deltaX;
}
{
deltaY;
}
}
Common Mistakes
Trying to loop over the enum type itself
This does not compile because Direction is a type, not an array or iterable collection.
// Does not compile
for (Direction direction : Direction) {
System.out.println(direction);
}
Call values():
for (Direction direction : Direction.values()) {
System.out.println(direction);
}
Using the wrong variable type
The loop variable must be the enum type, not String.
// Does not compile
for (String direction : Direction.values()) {
System.out.println(direction);
}
Use Direction:
for (Direction direction : Direction.values()) {
System.out.println(direction.name());
}
Assuming ordinal() is a stable business identifier
ordinal() gives the zero-based declaration position. It changes if constants are reordered or a new one is inserted.
Comparisons
| Approach | Best use | Notes |
|---|---|---|
Enhanced for with values() | Visit every enum value | Clearest choice when no index is needed. |
Indexed for loop | You need a position or neighboring array element | More verbose; use directions.length, not a hard-coded number. |
EnumSet.allOf(Direction.class) | You need a set of all values | Useful when performing set operations such as add, remove, or intersection. |
switch on one enum value | Choose behavior for a single known value | It selects a case; it does not iterate through all values. |
Stream.of(Direction.values()) | Stream transformations or collection pipelines |
Cheat Sheet
// Iterate over all constants
for (Direction direction : Direction.values()) {
System.out.println(direction);
}
// Save the generated array when reusing it
Direction[] directions = Direction.values();
// Iterate with an index
for (int i = 0; i < directions.length; i++) {
System.out.println(i + ": " + directions[i]);
}
// Get constant name
String name = Direction.NORTH.name(); // "NORTH"
// Get declaration position; do not use as persistent data
int position = Direction.NORTH.ordinal(); // 0
Key rules:
- Every Java enum automatically has
values(). values()returns constants in declaration order.- Use the enum type for the loop variable.
- Prefer the enhanced
forloop unless you truly need an index. - Do not rely on
ordinal()for database, file, or API values.
FAQ
How do I loop through all enum values in Java?
Call the enum's generated values() method and use an enhanced for loop:
for (Direction direction : Direction.values()) {
System.out.println(direction);
}
Does every Java enum have a values() method?
Yes. The Java compiler automatically creates values() for each enum. You do not write it yourself.
What order does Direction.values() return?
It returns constants in the order they appear in the enum declaration.
Can I use a normal for loop with an enum?
Yes. First store Direction.values() in an array, then loop from 0 to array.length - 1. This is useful when you need an index.
Can I change the values returned by values()?
You can change the returned array, but it does not change the enum. Each call provides an array that represents the enum constants.
Should I use ordinal() to identify an enum value?
Mini Project
Description
Create a small direction explorer for a grid-based application. It will iterate over every direction, display its movement offset, and calculate the neighboring coordinates from a starting position. This is the same pattern used in board games, pathfinding, image processing, and map tools.
Goal
Print every valid neighboring grid coordinate around a starting position by iterating through a Direction enum.
Requirements
Define a Direction enum containing the eight compass directions.
Associate each direction with an x and y movement offset.
Start from the coordinate (5, 5).
Use Direction.values() in an enhanced for loop.
Print the direction and its resulting coordinate for every enum constant.
Keep learning
Related questions
Add External JAR Files to an IntelliJ IDEA Java Project
Learn how to add external JAR dependencies to an IntelliJ IDEA Java project using module libraries, and when to use Maven or Gradle instead.
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Call a Method After a Delay in Android Java
Learn how to run Java code after a delay in Android using Handler.postDelayed, manage the main thread, and cancel callbacks safely.