Enums
An enum (enum) defines a fixed, named set of constants — for example, the days of the week, or the suits in a deck of cards. Java enums are type-safe: a variable of an enum type can only ever hold one of that enum's declared constants, and nothing else.
A basic enum
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class Main {
public static void main(String[] args) {
Day today = Day.WEDNESDAY;
System.out.println(today); // WEDNESDAY
}
}Enums are real classes, not just labeled ints
This is one of Java's most distinctive and powerful features compared to many other languages: an enum in Java is a genuine class. It can have fields, constructors, and methods, just like any other class — each constant is really a specific object of that class.
Planet.java — an enum with fields and a method
enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.37814e6);
private final double mass; // kilograms
private final double radius; // meters
// Every constant above calls this constructor with its own values
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
static final double G = 6.67300E-11;
double surfaceGravity() {
return G * mass / (radius * radius);
}
}
public class Main {
public static void main(String[] args) {
for (Planet p : Planet.values()) {
System.out.printf("Gravity on %s: %.2f m/s^2%n", p, p.surfaceGravity());
}
}
}Each constant — MERCURY, VENUS, EARTH — is a distinct object carrying its own mass and radius, constructed exactly once by the JVM when the Planet class is loaded, and surfaceGravity() is a completely ordinary instance method computed from that constant's own fields.
Using enums in a switch
switch on an enum
Day today = Day.SATURDAY;
switch (today) {
case SATURDAY:
case SUNDAY:
System.out.println("It's the weekend!");
break;
default:
System.out.println("Back to work.");
}Note that inside a switch on an enum, you write the bare constant name (SATURDAY), not Day.SATURDAY — the compiler already knows the type being switched on.
values() and valueOf()
Every enum automatically gets two useful static methods for free, generated by the compiler:
values()returns an array of every constant, in declaration order — used above to loop over all planets.valueOf(String name)converts a matching string back into the enum constant, throwingIllegalArgumentExceptionif no constant has that exact name.
values() and valueOf()
Day[] allDays = Day.values();
System.out.println(allDays.length); // 7
Day parsed = Day.valueOf("FRIDAY");
System.out.println(parsed); // FRIDAY
Day bad = Day.valueOf("Friday"); // throws IllegalArgumentException — case-sensitive