Java Enums
An enum (short for enumeration) is a special type that has a fixed set of named values — the days of the week, the suits in a card deck, the states of an order. Using an enum instead of plain strings or numbers means the compiler rejects invalid values and your IDE can autocomplete the valid ones.
Declaring an enum
enum Level {
LOW, MEDIUM, HIGH
}
class Main {
public static void main(String[] args) {
Level current = Level.MEDIUM;
System.out.println(current);
System.out.println(current == Level.MEDIUM);
System.out.println(current.name() + " has position " + current.ordinal());
}
}MEDIUM
true
MEDIUM has position 1
Enum constants are written in UPPER_CASE by convention. Each constant is a single object, so comparing with == is safe and idiomatic.
Enums in switch
Enums and switch are a perfect match. Inside the case labels you write the constant's name without the enum prefix:
enum TrafficLight {
RED, YELLOW, GREEN
}
class Main {
static String action(TrafficLight light) {
return switch (light) {
case RED -> "Stop";
case YELLOW -> "Slow down";
case GREEN -> "Go";
};
}
public static void main(String[] args) {
for (TrafficLight t : TrafficLight.values()) {
System.out.println(t + ": " + action(t));
}
}
}RED: Stop
YELLOW: Slow down
GREEN: Go
This switch expression needs no default: the compiler knows all three constants are covered. If you later add a BLINKING constant, the compiler will flag every switch that forgets it.
Built-in methods
| Method | Returns |
|---|---|
values() |
an array of all constants, in declaration order |
valueOf("NAME") |
the constant with that exact name (throws if none) |
name() |
the constant's name as a String |
ordinal() |
its 0-based position in the declaration |
compareTo(other) |
ordering by declaration position |
enum Size { SMALL, MEDIUM, LARGE, XL }
class Main {
public static void main(String[] args) {
Size s = Size.valueOf("LARGE");
System.out.println(s + " is bigger than MEDIUM: " + (s.compareTo(Size.MEDIUM) > 0));
System.out.println("Sizes available: " + Size.values().length);
try {
Size.valueOf("HUGE");
} catch (IllegalArgumentException e) {
System.out.println("No such size: HUGE");
}
}
}LARGE is bigger than MEDIUM: true
Sizes available: 4
No such size: HUGE
Enums with fields, constructors and methods
An enum is a full class. Its constants can carry data passed to a (private) constructor, and it can have methods:
enum Planet {
MERCURY(3.303e23, 2.4397e6),
EARTH(5.976e24, 6.37814e6),
JUPITER(1.9e27, 7.1492e7);
private static final double G = 6.67300E-11;
private final double mass; // kg
private final double radius; // m
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
double surfaceGravity() {
return G * mass / (radius * radius);
}
}
class Main {
public static void main(String[] args) {
double earthWeight = 70;
double massKg = earthWeight / Planet.EARTH.surfaceGravity();
for (Planet p : Planet.values()) {
System.out.printf("Weight on %-8s %6.1f%n", p, massKg * p.surfaceGravity());
}
}
}Weight on MERCURY 26.4
Weight on EARTH 70.0
Weight on JUPITER 177.1
Constants can even override methods individually, and enums can implement interfaces:
interface Operation {
int apply(int a, int b);
}
enum BasicOp implements Operation {
PLUS("+") {
public int apply(int a, int b) { return a + b; }
},
TIMES("*") {
public int apply(int a, int b) { return a * b; }
};
private final String symbol;
BasicOp(String symbol) { this.symbol = symbol; }
String symbol() { return symbol; }
}
class Main {
public static void main(String[] args) {
for (BasicOp op : BasicOp.values()) {
System.out.println("6 " + op.symbol() + " 7 = " + op.apply(6, 7));
}
}
}6 + 7 = 13
6 * 7 = 42
Tip: For maps and sets keyed by an enum, use
EnumMapandEnumSetfromjava.util. They are extremely fast and keep entries in declaration order.
Test yourself
What does Day.values() return?
- The number of constants
- An array of all constants in declaration order
- A random constant
- A list of names as strings
Given enum Color { RED, GREEN, BLUE }, what is Color.BLUE.ordinal()?
- 0
- 1
- 2
- 3
Can an enum have fields and a constructor?
- No, only constants
- Yes, and the constructor is implicitly private
- Yes, but the constructor must be public
- Only static fields