Java Enum values() Method
Example
Loop through all the constants of an enum:
public class Main {
enum Level { LOW, MEDIUM, HIGH }
public static void main(String[] args) {
for (Level myVar : Level.values()) {
System.out.println(myVar);
}
}
}
Definition and Usage
The values() method returns an array with all the constants of the enum, in the order they are written in the enum.
You do not write this method yourself. The Java compiler adds it to every enum that you create. It is often used to loop through the constants.
Tip: To count the constants, use the length of the array: Level.values().length.
Syntax
public static E[] values()
E refers to the enum type, for example Level.
Parameter Values
None.
Technical Details
| Returns: | An array with all the constants of the enum. |
|---|
Related Pages
Java Enum Constructor Tutorial
❮ Enum Methods