Enums and enum methods
What you will learn
An enum gives a type a fixed set of named choices. Use it when a value must be one of several known states, such as a delivery stage. Unlike a string, an enum prevents misspelled choices from compiling; unlike an integer code, it carries a meaningful name.
- Declare an enum and use its constants and methods.
- Choose an enum-specific set or map and interpret its ordering.
Use a fresh folder for each complete Main.java example. Compile with javac --release 21 Main.java and run java Main. Requires JDK 21 or a compatible newer JDK. The examples use the standard library only.
Choose a delivery stage
public class Main { enum Stage { QUEUED, PACKED, SENT } public static void main(String[] args) { Stage stage = Stage.PACKED; System.out.println(stage == Stage.PACKED); System.out.println(switch (stage) { case QUEUED -> "Waiting"; case PACKED -> "Ready"; case SENT -> "On the way"; }); }}Expected output:
trueReadyThe variable can hold a Stage constant or null. Each named constant has a unique instance, so == is appropriate. The switch expression handles each declared constant and produces a label.
Rules and mental model
An enum is a special class, not a string alias. Its constants may have fields and methods and even distinct method implementations. Its constructor cannot be public or protected, and clients cannot use new to create more constants. An enum reference may still be null. Use name() for the declared identifier; toString() may be overridden. ordinal() is a zero-based position, not a durable business identifier. EnumSet and EnumMap are mutable, single-enum-type containers; neither is automatically thread-safe. EnumSet rejects null elements, and EnumMap rejects null keys but permits null values.
Attach a delivery duration to each choice
public class Main { enum Speed { STANDARD(4), EXPRESS(1); private final int days; Speed(int days) { this.days = days; } int days() { return days; } } public static void main(String[] args) { for (Speed speed : Speed.values()) { System.out.println(speed.name() + ": " + speed.days()); } System.out.println(Speed.valueOf("EXPRESS") == Speed.EXPRESS); }}Expected output:
STANDARD: 4EXPRESS: 1trueThe semicolon ends the constants before the fields and methods. Constructor arguments supply per-constant data. values() gives the constants in declaration order. valueOf requires an exact name, including case; it is not a friendly user-input parser.
Store selected features and per-feature quantities
import java.util.EnumSet;import java.util.EnumMap;public class Main { enum Feature { WRAP, CARD, TRACKING } public static void main(String[] args) { EnumSet<Feature> selected = EnumSet.of(Feature.TRACKING, Feature.WRAP); EnumMap<Feature, Integer> quantities = new EnumMap<>(Feature.class); quantities.put(Feature.TRACKING, 1); quantities.put(Feature.WRAP, 2); System.out.println(selected); System.out.println(quantities); System.out.println(selected.contains(Feature.CARD)); }}Expected output:
[WRAP, TRACKING]{WRAP=2, TRACKING=1}falseA set stores distinct selections; a map associates a key with a value. The angle brackets restrict the types (Integer is the boxed form of int). Feature.class identifies the key type. Both iterate in declaration order, not insertion order. Collections and generics are covered in depth later.
Common mistakes
Do not store ordinal() as a long-lived database code: inserting a constant can change later positions. Prefer an explicitly defined stable code and validate incoming text. A switch on a null enum without a null case throws NullPointerException. Java 21 supports explicit case null in enhanced switches, but an ordinary enum switch does not accept null automatically.
Practice
Model workshop access with enum Pass { DAY(1), WEEK(7), MONTH(30) }. Implement days(), put WEEK and DAY into an EnumSet, and print their durations in declaration order followed by whether MONTH is selected. Verify an empty selection as well. Do not use ordinal as a duration.
Check your result with the chapter practice task and explain why it works.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Enums and enum methods — knowledge check
Apply enum, record and ownership rules using Java 21-compatible examples.
Why is Stage.PACKED == Stage.PACKED true?
What does Speed.valueOf("express") do in the delivery example?
Why should you avoid persisting ordinal() as a business code?
If TRACKING is added before WRAP, how does the example EnumSet iterate?
Which container associates a quantity with each feature?