Skip Top Navigation Bar

Iterating Over an Enum

Enhanced For Loops

An enhanced for loop can be used to iterate over a set of values.

General Format

for (<Variable Declaration> : <Set of Values>) {
   //body
}

The keyword for is followed by parenthesis and a variable declaration that is the same type as the values in the set. This is followed by a colon (:), followed by the set of values that we will be iterating over.

Iterating Over an Enum

We can use the enhanced for loop to iterate over an enum. The values that are iterated over are those that are the constants in the enum.

Consider the following enum example.

enum Directions { 
    NORTH, SOUTH, EAST, WEST
}

The values that we will iterate over are NORTH, SOUTH, EAST, WEST. The type of these constants are Directions.

Accessing the Values of an enum

To access the values of an enum, we will need to use the values() method. This method return the constants in the order that they are listed in the declaration.

Try this in the Java Playground.

Resources