An enum is a special type used to represent a fixed set of constants.
Use enums when a value can only be one of a predefined set of options.
enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
Now:
Day today = Day.MONDAY;
today can only contain one of the defined Day values.
Instead of using strings:
String status = "SUCCESS";
you can use:
enum Status {
PENDING,
SUCCESS,
FAILED
}
Status status = Status.SUCCESS;
This gives you type safety and prevents invalid values.
Status status = Status.INVALID; // ❌
Enums can contain fields, constructors, and methods, just like classes.
enum Status {
PENDING,
SUCCESS,
FAILED;
void print() {
System.out.println(this);
}
}
Status.SUCCESS.print();