In Java, enums (short for enumerations) are a special type of class used to define a fixed set of constants. They’re type-safe, more powerful than just using final static
constants, and can even have methods, fields, and constructors.
1. Basic Syntax
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Here, Day
is an enum type, and each value (like MONDAY
) is a constant instance of that type.
2. How to Use
public class EnumExample {
public static void main(String[] args) {
Day today = Day.MONDAY;
if (today == Day.MONDAY) {
System.out.println("Start of the work week!");
}
// Loop through all values
for (Day d : Day.values()) {
System.out.println(d);
}
}
}
Output:
Start of the work week!
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
3. Enums Can Have Fields, Methods, and Constructors
enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.37814e6);
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double surfaceGravity() {
final double G = 6.67300E-11;
return G * mass / (radius * radius);
}
}
You can call:
System.out.println(Planet.EARTH.surfaceGravity());
4. Key Features
- Type safety: You can’t assign an invalid value to an enum variable.
values()
method: Returns an array of all enum constants.ordinal()
method: Returns the position of the enum constant (starting at 0).valueOf()
method: Returns the enum constant by name.
5. Enums in switch
Statements
Day day = Day.FRIDAY;
switch (day) {
case MONDAY:
System.out.println("Work again...");
break;
case FRIDAY:
System.out.println("Weekend incoming!");
break;
default:
System.out.println("Just another day.");
}