Question

Iterate Over Enum Values with a For Loop in Java

javaloopsfor-loopenums

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.

Take Quiz

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();

for (int index = 0; 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:

  1. Direction.values() creates an array containing all declared constants:

    [NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST]
    
  2. The loop assigns the first array element, NORTH, to direction.

    Moving NORTH
    
  3. It assigns NORTHEAST to direction and prints it.

    Moving NORTHEAST
    
  4. The loop continues once for every remaining constant.

  5. After NORTHWEST is 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 Direction when 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);
}
Take Quiz

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(1, 0),
    SOUTHEAST(1, 1),
    SOUTH(0, 1),
    SOUTHWEST(-1, 1),
    WEST(-1, 0),
    NORTHWEST(-1, -1);

    private final int deltaX;
    private final int deltaY;

    Direction(int deltaX, int deltaY) {
        this.deltaX = deltaX;
        this.deltaY = deltaY;
    }

    public int getDeltaX() {
        return deltaX;
    }

    public int getDeltaY() {
        return deltaY;
    }
}

Then the loop can use each direction's behavior directly:

for (Direction direction : Direction.values()) {
    int nextX = x + direction.getDeltaX();
    int nextY = y + direction.getDeltaY();
    System.out.println(nextX + ", " + nextY);
}

For a small fixed enum, calling values() directly is usually perfectly readable. If a performance-sensitive method loops repeatedly, store the result once in a private static field because values() returns a new array each time it is called.

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.

int position = Direction.EAST.ordinal(); // Currently 2

Avoid storing ordinals in files, databases, or API payloads. Use name() only when its exact text is an intentional contract, or define a separate stable field such as a code.

Modifying the array returned by values() and expecting enum constants to change

values() returns an array copy. Changing that array does not add, remove, or reorder enum constants.

Direction[] directions = Direction.values();
directions[0] = Direction.SOUTH;

System.out.println(Direction.values()[0]); // Still NORTH

Forgetting that declaration order matters

A values() loop follows the order in the enum declaration. If your application depends on clockwise traversal, declare the values clockwise or create an explicit ordering method.

Comparisons

ApproachBest useNotes
Enhanced for with values()Visit every enum valueClearest choice when no index is needed.
Indexed for loopYou need a position or neighboring array elementMore verbose; use directions.length, not a hard-coded number.
EnumSet.allOf(Direction.class)You need a set of all valuesUseful when performing set operations such as add, remove, or intersection.
switch on one enum valueChoose behavior for a single known valueIt selects a case; it does not iterate through all values.
Stream.of(Direction.values())Stream transformations or collection pipelinesUseful for filtering or mapping, but often unnecessary for a simple loop.

Example using EnumSet:

import java.util.EnumSet;

for (Direction direction : EnumSet.allOf(Direction.class)) {
    System.out.println(direction);
}

For simple traversal, Direction.values() remains the idiomatic and direct choice.

Take Quiz

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 for loop 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?

Usually no. Ordinals depend on declaration order and can change when the enum evolves. Define a stable field if you need to store or transmit an identifier.

Can an enum contain methods and fields?

Yes. Enums can have constructors, fields, and methods, which makes them useful for associating data and behavior with each constant.

Take Quiz

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.

Take Quiz

Keep learning

Related questions

View more