In Java, every enum automatically provides a values() method that returns an array containing all enum constants in the order they are declared. This makes it easy to process, display, or perform operations on every enum constant without manually listing them.
Key Points:
• The values() method is automatically generated by the Java compiler for every enum. • It returns all enum constants as an array in declaration order. • Commonly used in loops, dropdown generation, validation, and reporting. • Helps write maintainable code because new enum constants are automatically included during iteration.
Example:
Suppose an application has an enum representing the days of the week. Using values(), you can easily display all available days without hardcoding each value.
Code Example:
enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY
}
public class EnumDemo {
public static void main(String[] args) {
for (Day day : Day.values()) {
System.out.println(day);
}
}
}Interview Tip:
A concise interview answer is: "To iterate over all enum constants in Java, use the values() method. It returns an array of all enum values, which can be traversed using a for-each loop."