An enum is a special class representing a fixed group of constants, such as days, levels or order statuses.
Declare: enum Level { LOW, MEDIUM, HIGH }
Use: Level l = Level.HIGH;
Loop: for (Level x : Level.values())
Enums work well with switch and can have fields and methods.
💡 Key Takeaways: Java Enums
Mastering Java Enums helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
Java Enums Code Example
Java
enum Status {
PENDING("Waiting"), SHIPPED("On the way"), DELIVERED("Arrived");
private final String label;
Status(String label) { this.label = label; }
String label() { return label; }
}
public class Main {
public static void main(String[] args) {
for (Status s : Status.values()) {
System.out.println(s + " -> " + s.label());
}
Status order = Status.valueOf("SHIPPED");
System.out.println(order.ordinal());
}
}
Output
PENDING -> Waiting
SHIPPED -> On the way
DELIVERED -> Arrived
1
Run this example on your own computer. The "Get Started" lesson shows how to set it up.