values and valueOf
- Java course
- Beginner
- Lesson 101/116
- 4 min
Learn enum operations with values() and valueOf().
values returns all constants
values() returns all constants of an enum as an array. valueOf(String) obtains a constant from a name. These are the core tools for looping and conversion.
for (Day d : Day.values()) {
System.out.println(d);
}
Day d = Day.valueOf("MONDAY");values() creates a new array on each call, but for small enums this does not matter. valueOf throws IllegalArgumentException if the name is not found, so you should validate input. Together they make it easy to iterate over an enum.
Iterate constants with for-each
The array returned by values() makes a for-each loop easy to write. This is the most common way to list all options of an enum.
for (Day d : Day.values()) {
System.out.println(d + " " + d.ordinal());
}The loop order matches the declaration order, so the output is predictable. This pattern is very handy for listing menu options or processing all states. You can also access the ordinal with ordinal().
Practice List all days
Define the Day enum (MONDAY through SUNDAY). Build a for-each loop over values() and print each day on its own line.
Starter code
public class Main {
public static void main(String[] args) {
// Define the Day enum, loop with values(), print
}
}
// Define the Day enum hereSample solution
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
// inside main:
for (Day d : Day.values()) {
System.out.println(d);
}Expected output
MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Day.valueOf("MONDAY") return?
- An array
- The string "MONDAY"
- 0
- The Day.MONDAY constant Correct answer
Explanation: valueOf obtains an enum constant from a name; it returns the constant itself, not a string.
2 Match each method to its return type
| Term | Meaning |
|---|---|
values() |
Day[] |
valueOf(String) |
Day |
ordinal() |
int |
name() |
String |
3 Find a constant with valueOf
Day d = Day.____("MONDAY");
Day d = Day.valueOf("MONDAY");
Explanation: valueOf produces a constant from a name.