An enum in Java is a special data type used to define a fixed set of constant values. It improves code readability, safety, and prevents invalid values.
java.lang.EnumEnums are declared using the enum keyword. Each constant is separated by a comma and written in uppercase by convention.
// Basic enum declaration representing days of the week
enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
// Using enum in a Java program
enum Status {
SUCCESS,
FAILURE,
PENDING
}
public class Main {
public static void main(String[] args) {
Status currentStatus = Status.SUCCESS;
System.out.println(currentStatus);
}
}
The program prints the enum constant: SUCCESS
See how an enum TrafficLight works in real-time. Click the button to change states!
public static final)values()