In Java, an enum
(short for “enumeration”) is a special data type used to define a collection of constants. Each constant in an enum
is implicitly public
, static
, and final
. Enums are commonly used when a variable can take only a limited set of values, such as days of the week, directions, or states in a finite state machine.
Basic Example
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
public class EnumExample {
public static void main(String[] args) {
Day today = Day.FRIDAY;
if (today == Day.FRIDAY) {
System.out.println("It's almost the weekend!");
}
// Loop through all enum values
for (Day d : Day.values()) {
System.out.println(d);
}
}
}
Output:
It's almost the weekend!
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
Enum with Fields, Constructor, and Methods
Enums can have attributes, constructors, and methods.
enum Size {
SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRALARGE("XL");
private String abbreviation;
// Constructor
Size(String abbreviation) {
this.abbreviation = abbreviation;
}
public String getAbbreviation() {
return abbreviation;
}
}
public class EnumWithFields {
public static void main(String[] args) {
Size size = Size.MEDIUM;
System.out.println("Size: " + size);
System.out.println("Abbreviation: " + size.getAbbreviation());
}
}
Output:
Size: MEDIUM
Abbreviation: M
Enum in Switch Statement
Enums work well with switch
statements.
public class EnumSwitchExample {
enum TrafficLight {
RED, YELLOW, GREEN
}
public static void main(String[] args) {
TrafficLight signal = TrafficLight.RED;
switch (signal) {
case RED:
System.out.println("Stop!");
break;
case YELLOW:
System.out.println("Get ready...");
break;
case GREEN:
System.out.println("Go!");
break;
}
}
}
Output:
Stop!
Enum Implementing an Interface
Enums can implement interfaces.
interface Describable {
String getDescription();
}
enum Status implements Describable {
SUCCESS("Operation successful"),
ERROR("Operation failed"),
PENDING("Operation pending");
private String description;
Status(String description) {
this.description = description;
}
@Override
public String getDescription() {
return description;
}
}
public class EnumInterfaceExample {
public static void main(String[] args) {
Status s = Status.SUCCESS;
System.out.println(s + ": " + s.getDescription());
}
}
Output:
SUCCESS: Operation successful
Key Features of Enums in Java
- Type-safe and prevent invalid values.
- Can have fields, methods, and constructors.
- Can implement interfaces but cannot extend classes.
- Can be used in switch statements.
- The
values()
method returns all possible values of an enum.
Enums are widely used in Java for defining fixed sets of constants, making code more readable and maintainable.