Java Enums: Values, Constructors, Fields, Methods and switch (OCP 21)
Java enums for the OCP 21 exam: simple enums, values(), name(), ordinal() and valueOf(), enums in switch (including qualified case labels new in Java 21), complex enums with fields and private constructors, constant-specific bodies, abstract methods and interfaces.
kvi5hnuCode Sprout team member7 min readOn this page
An enum (enumeration) is a type with a fixed set of named instances, such as the days of the week, card suits or order states. Before enums existed, programs used int or String constants, and the compiler couldn't stop someone from passing 7 or "pendng". An enum makes invalid values impossible: a parameter of type OrderState can only ever be one of its constants, or null.
Simple enums
public enum Tide { LOW, RISING, HIGH, FALLING } // trailing ; optional here
Each constant is a public static final instance of Tide, and it's created exactly once, when the enum is initialized. The naming convention is upper-case snake case, such as COLD_BREW.
Tide t = Tide.HIGH;
System.out.println(t); // HIGH (toString() returns the name)
System.out.println(t == Tide.HIGH); // true: one instance per constant, so == is safe
Because each constant is unique, == and equals() always give the same result for enums, and == is the usual choice.
What you can't do with an enum:
enum BigTide extends Tide { } // DOES NOT COMPILE: enums can't extend anything
final enum Tide2 { A } // DOES NOT COMPILE: modifier final not allowed here
Tide x = new Tide(); // DOES NOT COMPILE: enum classes may not be instantiated
if (Tide.HIGH == 2) { } // DOES NOT COMPILE: bad operand types (Tide vs int)
Every enum implicitly extends java.lang.Enum, so it can't extend another class. It can implement interfaces. An enum can't be extended by your code: it is implicitly final, or implicitly sealed when some constants have their own bodies (those bodies are its only subclasses, see below). A nested enum is implicitly static.
Built-in methods
| Method | Returns | Example with Tide |
|---|---|---|
values() (static) | a new array of all constants, in declaration order | [LOW, RISING, HIGH, FALLING] |
valueOf(String) (static) | the constant with exactly that name | Tide.valueOf("HIGH") → HIGH |
name() | the declared name (final, can't be overridden) | "HIGH" |
ordinal() | zero-based position in the declaration | HIGH.ordinal() → 2 |
compareTo(E) | compares ordinals | LOW.compareTo(HIGH) → negative |
toString() | name() by default, can be overridden | "HIGH" |
for (Tide t : Tide.values()) {
System.out.print(t.name() + t.ordinal() + " "); // LOW0 RISING1 HIGH2 FALLING3
}
Tide.valueOf("high"); // IllegalArgumentException: No enum constant Tide.high
valueOf is case-sensitive and throws IllegalArgumentException for an unknown name (and NullPointerException for null). It doesn't create anything. It looks up an existing constant.
Avoid relying on ordinal() in your own logic. Inserting a constant later shifts every ordinal after it.
Enums in switch
Enums work in both switch statements and switch expressions (articles 12 and 13). A switch expression over an enum is exhaustive if it covers every constant, so it doesn't need a default:
static String advice(Tide t) {
return switch (t) {
case LOW, FALLING -> "walk the beach";
case RISING -> "head back";
case Tide.HIGH -> "stay ashore"; // qualified name: allowed since Java 21
};
}
Points the exam checks:
- Unqualified names (
case LOW) have always worked. Qualified names (case Tide.HIGH) are new in Java 21. Before that, javac rejected them with "an enum switch case label must be the unqualified name of an enumeration constant". - An ordinal isn't a label.
case 0 ->fails with "int cannot be converted to Tide". - A switch expression that leaves out a constant without a
defaultfails with "the switch expression does not cover all possible input values". An old-style switch statement with no patterns doesn't have to be exhaustive. - Switching on a
nullenum reference throwsNullPointerException, unless the switch has acase null(Java 21).
Complex enums: fields, constructors and methods
An enum can have fields, constructors, methods and even a main method:
public enum Planet {
MERCURY(3.30e23, 2.44e6), EARTH(5.97e24, 6.37e6), JUPITER(1.90e27, 6.99e7); // ; required now
private final double mass; // kg
private final double radius; // m
Planet(double mass, double radius) { // implicitly private
this.mass = mass;
this.radius = radius;
}
double surfaceGravity() { return 6.67e-11 * mass / (radius * radius); }
}
The rules:
- The constant list comes first. Writing a field before the constants fails with "enum constant expected here".
- A semicolon must end the list when anything follows it. A missing
;is a syntax error. - The arguments after each constant are constructor calls, without
new. - Constructors are implicitly
private. Writingprivateis optional, andpublicorprotectedfails with "modifier public not allowed here". - Fields should be
private final. Every constant is a JVM-wide singleton, so a mutable field is shared global state. That compiles, but it's a poor design.
When constructors run
All constants are constructed together, the first time the enum is used, in declaration order. They're never constructed again:
enum Gear {
LOW("l"), HIGH("h");
Gear(String c) { System.out.print("make " + c + ","); }
}
System.out.print("start,");
var g = Gear.HIGH; // first use: builds LOW, then HIGH
System.out.print("mid,");
var h = Gear.LOW; // nothing printed
System.out.println("end");
// start,make l,make h,mid,end
Because the constants are created during static initialization, before the enum's other static fields are set, a constructor can't read a non-constant static field of its own enum. count++ on a static int count fails with "illegal reference to static field from initializer". Compile-time constants (static final int MAX = 3) are fine.
Constant-specific bodies
A constant can have its own class body, which overrides methods for that constant only:
enum Shift {
DAY { String hours() { return "08-16"; } },
NIGHT { String hours() { return "22-06"; } },
SWING; // uses the enum's own version
String hours() { return "14-22"; }
}
If the enum declares an abstract method, every constant must implement it. The enum itself isn't marked abstract:
enum Shift {
DAY { String hours() { return "08-16"; } },
NIGHT; // DOES NOT COMPILE: javac reports "Shift is abstract; cannot be instantiated"
abstract String hours();
}
A constant with a body is an instance of an anonymous subclass of the enum. DAY.getClass() is Shift$1, while DAY.getDeclaringClass() is Shift. This is the only way an enum can have subclasses.

Enums and interfaces
An enum can implement interfaces. It implements the methods either once for all constants, or separately in each constant's body:
interface Priced { int priceCents(); }
enum Size implements Priced {
SMALL(250), LARGE(400);
private final int cents;
Size(int cents) { this.cents = cents; }
public int priceCents() { return cents; } // public: it implements an interface method
}
Priced p = Size.LARGE; // an enum constant used through the interface type
If the enum leaves an interface method unimplemented, it fails to compile, unless every constant implements it.
What's current
- Qualified enum constants in
caselabels (case Tide.HIGH) arrived in Java 21. They're current and on 1Z0-830. - Nothing else about enums changed in Java 22 through 25. The compiler insists on covering every constant (or adding
default) only for aswitchexpression or a patternswitch. An old-styleswitchstatement over an enum may skip constants.
Exam traps from this article
A complete example
The program defines a complex Drink enum (with fields, a constructor, an interface implementation and two constant-specific bodies) and a simple Size enum. It then uses values(), valueOf(), a switch expression, compareTo and an EnumMap.
import java.util.EnumMap;
import java.util.Map;
public class Solution {
interface Priced {
int priceCents();
}
// A complex enum: constants first, then fields, constructor and methods
enum Drink implements Priced {
ESPRESSO(250, 60),
LATTE(380, 240) {
@Override String note() { return "steamed milk"; } // constant-specific body
},
TEA(220, 300),
COLD_BREW(420, 350) {
@Override String note() { return "served cold"; }
}; // ; required: members follow
private final int priceCents;
private final int volumeMl;
Drink(int priceCents, int volumeMl) { // implicitly private
this.priceCents = priceCents;
this.volumeMl = volumeMl;
}
@Override public int priceCents() { return priceCents; }
int volumeMl() { return volumeMl; }
String note() { return "-"; } // default for most constants
}
enum Size { SMALL, MEDIUM, LARGE } // a simple enum
static double factor(Size size) {
return switch (size) { // exhaustive: no default needed
case SMALL -> 0.8;
case MEDIUM -> 1.0;
case Size.LARGE -> 1.3; // qualified label: Java 21+
};
}
public static void main(String[] args) {
for (Drink d : Drink.values()) {
System.out.printf("%d %-9s %4d ml %s%n", d.ordinal(), d.name(), d.volumeMl(), d.note());
}
Drink order = Drink.valueOf("LATTE"); // exact, case-sensitive name
Size size = Size.valueOf("LARGE");
long cents = Math.round(order.priceCents() * factor(size));
System.out.println(order + " " + size + " costs " + cents + " cents");
try {
Drink.valueOf("latte");
} catch (IllegalArgumentException e) {
System.out.println("valueOf failed: " + e.getMessage());
}
System.out.println("LATTE == valueOf: " + (order == Drink.LATTE));
System.out.println("TEA vs LATTE compareTo: " + Drink.TEA.compareTo(Drink.LATTE));
System.out.println("LATTE class: " + Drink.LATTE.getClass().getSimpleName().isEmpty()
+ ", declaring class: " + Drink.LATTE.getDeclaringClass().getSimpleName());
Map<Size, Integer> sold = new EnumMap<>(Size.class); // keys kept in ordinal order
sold.merge(Size.LARGE, 1, Integer::sum);
sold.merge(Size.SMALL, 2, Integer::sum);
sold.merge(Size.LARGE, 1, Integer::sum);
System.out.println("sold: " + sold);
}
}
Output:
0 ESPRESSO 60 ml -
1 LATTE 240 ml steamed milk
2 TEA 300 ml -
3 COLD_BREW 350 ml served cold
LATTE LARGE costs 494 cents
valueOf failed: No enum constant Solution.Drink.latte
LATTE == valueOf: true
TEA vs LATTE compareTo: 1
LATTE class: true, declaring class: Drink
sold: {SMALL=2, LARGE=2}
Points to notice:
LATTEandCOLD_BREWoverridenote(). The others inherit the enum's version, which returns"-".- The switch in
factorhas nodefault. Covering all three sizes makes it exhaustive, andcase Size.LARGEuses the Java 21 qualified form. TEA.compareTo(LATTE)is positive becauseTEAis declared later (ordinal 2 > 1).LATTE.getClass()is an anonymous class, which has an empty simple name, butgetDeclaringClass()is stillDrink.EnumMapprints its keys in declaration order, not insertion order.Integer::sumis a method reference, covered in chapter 8.
Common questions
Can an enum have a main method or static methods?
Yes. An enum can contain anything a class can, except that its constructors are private and it can't extend other types.
Should I compare enums with == or equals?
== is preferred. It's null-safe on the left-hand side, and the compiler checks that both sides have compatible types.
Are enums good for singletons?
Yes. A single-constant enum (enum Registry { INSTANCE; ... }) is a well-known and safe way to write a singleton, including under serialization.
What changed for enums in recent Java versions?
Java 21 added qualified enum constants as case labels, plus pattern matching and case null in switch. Enums can also be used as the permitted subtypes of sealed interfaces (article 40).
Summary
- An enum is a fixed set of singleton constants. Compare them with
==. Enums can't be extended, instantiated or declaredfinal, but they can implement interfaces. values(),valueOf(),name(),ordinal()andcompareTo()come built in.valueOfis exact and throwsIllegalArgumentExceptionfor unknown names.- In a switch, use constant names (qualified names are allowed since Java 21). Switch expressions must cover every constant or have a
default. - Complex enums list their constants first and end the list with
;. Constructors are private and run once per constant on first use. - Constant-specific bodies override methods, and an abstract enum method must be implemented by every constant.
Practice quiz
Test yourself with the enums quiz: 10 exam-style questions with explanations.
Previous: Java Interface default, static and private Methods (OCP 21)
Next: Java Sealed Classes and Interfaces: sealed, permits, final and non-sealed (OCP 21)
Related reading
- Java Interface default, static and private Methods (OCP 21)
- Java Interfaces: Declaring, Implementing and Inheriting Abstract Methods (OCP 21)
- Java Immutable Objects and Defensive Copies (OCP 21)
- Java Abstract Classes and Abstract Methods (OCP 21)
- Java Method Overriding and Hiding: Rules, final Methods and Static Hiding (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.