An enum names a fixed set of alternatives. It replaces spelling-sensitive strings such as "todo" and "done" with compiler-checked values. Use an enum when the set is deliberately closed, not for arbitrary user-defined labels.
Work through the example
Status is a type. TODO and DONE are its named constants; Status.TODO selects one. Comparing enum constants with == is appropriate. This example keeps the mapping from status to display text in one method. A new constant means that decision deserves review.
The method returns the existing DONE constant rather than modifying a task. Each enum constant is a fixed value; this call does not construct a fresh enum object. The helpers below reject null explicitly, since null is not a status. Separating a transition from storage makes it easy to check. State modeling becomes useful when a task tracker must distinguish open work from completed work without accepting arbitrary strings.
Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.
public class Main {
public static void main(String[] args) {
Status status = Status.TODO;
System.out.println(label(status));
status = complete(status);
System.out.println(label(status));
System.out.println(complete(status) == Status.DONE);
}
static Status complete(Status status) {
if (status == null) {
throw new IllegalArgumentException("status required");
}
return Status.DONE;
}
static String label(Status status) {
if (status == null) {
throw new IllegalArgumentException("status required");
}
if (status == Status.TODO) {
return "Open";
}
return "Complete";
}
}
enum Status {
TODO,
DONE
}Check your prediction
Open
Complete
trueCompare the behavior
Parsing text is a boundary operation. valueOf expects the constant's exact name and throws IllegalArgumentException for unknown names. Convert only where the application's input policy says to. Do not scatter conversions throughout the model. Here lowercase text is rejected explicitly, and the Day 7 project's parser keeps the same strict rule: a line whose status is todo is reported as a bad line.
public class Main {
public static void main(String[] args) {
System.out.println(Status.valueOf("TODO"));
try {
System.out.println(Status.valueOf("todo"));
} catch (IllegalArgumentException error) {
System.out.println("Unknown status");
}
}
}
enum Status {
TODO,
DONE
}Check your prediction
TODO
Unknown statusSeparate a fixed choice from the state transition
An enum type restricts a source-code value to named alternatives, while a
transition method decides what happens next. The compiler can reject
Status.DOEN as a nonexistent constant, but it cannot decide whether completing
an already completed task should be allowed. That is the operation's rule:
| Status before | complete(status) |
|---|---|
| TODO | DONE |
| DONE | DONE (repeating has no further effect) |
| null | IllegalArgumentException |
A toggle would differ in the second row. Text input still needs parsing at one boundary, so the rest of the model works with the enum, not with spellings.
Let the compiler check every constant
The label method above ends with a fallback: anything that is not TODO is
"Complete". That is fine while there are two constants. Add a third and the
fallback silently gives it the wrong answer. A switch expression over an
enum avoids this. Each case names one constant, the -> gives that case's
value, and with no default branch the compiler checks that every constant is
covered.
public class Main {
public static void main(String[] args) {
System.out.println(label(Status.TODO));
System.out.println(label(Status.DONE));
}
static String label(Status status) {
if (status == null) {
throw new IllegalArgumentException("status required");
}
return switch (status) {
case TODO -> "Open";
case DONE -> "Complete";
};
}
}
enum Status {
TODO,
DONE
}Check your prediction
Open
CompleteNow add BLOCKED to the enum and run again. The program no longer compiles:
Main.java:11: error: the switch expression does not cover all possible input values
return switch (status) {
^That error is the point. The compiler has found the one decision you must
revisit. Add case BLOCKED -> "Waiting"; and it runs again. A default ->
branch would have hidden the problem just as the if/else fallback did. The null
check stays: a switch on a null enum throws NullPointerException.
An enum constant can also carry data. Here each priority stores its own minutes,
and values() returns every constant in declaration order:
public class Main {
public static void main(String[] args) {
for (Priority priority : Priority.values()) {
System.out.println(priority + " " + priority.minutes());
}
}
}
enum Priority {
LOW(10),
HIGH(25);
private final int minutes;
Priority(int minutes) {
this.minutes = minutes;
}
int minutes() {
return minutes;
}
}Check your prediction
LOW 10
HIGH 25LOW(10) calls the enum's constructor once, when the class loads. With this
design a new constant cannot even be written without its minutes. Use a field
when the value belongs to the constant itself; use a switch when the decision
belongs to one method (a label for one screen, say).
Practice independently
Enums & State: practice
Create Priority with LOW and HIGH. Write minutesFor(Priority) using a switch
expression with no default: 10 for LOW and 25 for HIGH. Reject a null argument
with priority required; null is not an enum constant. Print both valid results
and the rejection message:
10
25
priority requiredpublic class Main {
public static void main(String[] args) {
System.out.println("Add Priority and minutesFor");
}
}Hint 1: the idea
A fixed set of named alternatives belongs in one enum. The method makes one decision per constant, and the compiler should be able to confirm none is missing.
Hint 2: a first step
Write the enum first, then start minutesFor with the null check. After it,
return switch (priority) { with one case ... -> line per constant, closed by
};.
Show one solution
public class Main {
public static void main(String[] args) {
System.out.println(minutesFor(Priority.LOW));
System.out.println(minutesFor(Priority.HIGH));
try {
minutesFor(null);
} catch (IllegalArgumentException error) {
System.out.println(error.getMessage());
}
}
static int minutesFor(Priority priority) {
if (priority == null) {
throw new IllegalArgumentException("priority required");
}
return switch (priority) {
case LOW -> 10;
case HIGH -> 25;
};
}
}
enum Priority {
LOW,
HIGH
}Expected output:
10
25
priority requiredThe null check runs before the switch so the caller gets the stated message instead of a NullPointerException. The switch has no default, so adding a constant to Priority later turns this method into a compile error until the new constant gets its own minutes.
Debug a plausible mistake
This code was written before switch expressions were adopted, with an if/else fallback. Then MEDIUM was added to the enum. Everything still compiles.
Repair a new enum alternative
MEDIUM must map to 15 minutes. Keep LOW at 10 and HIGH at 25, so the three calls
print 10, 15 and 25. Predict what the current program prints before changing
it. Fix it so that the next new constant cannot slip through the same way: when
you are done, adding URGENT to the enum should stop the program compiling.
Keep the null check.
public class Main {
public static void main(String[] args) {
System.out.println(minutes(Priority.LOW));
System.out.println(minutes(Priority.MEDIUM));
System.out.println(minutes(Priority.HIGH));
}
static int minutes(Priority priority) {
if (priority == null) {
throw new IllegalArgumentException("priority required");
}
if (priority == Priority.HIGH) {
return 25;
}
return 10;
}
}
enum Priority {
LOW,
MEDIUM,
HIGH
}Hint 1: the idea
The bug is not only a missing number: the final return 10; answers for every
constant nobody thought about. The fix should remove that silent answer.
Hint 2: a first step
Replace the HIGH check and the final return with a switch expression over priority that has one case for each of the three constants and no default.
Show one solution
public class Main {
public static void main(String[] args) {
System.out.println(minutes(Priority.LOW));
System.out.println(minutes(Priority.MEDIUM));
System.out.println(minutes(Priority.HIGH));
}
static int minutes(Priority priority) {
if (priority == null) {
throw new IllegalArgumentException("priority required");
}
return switch (priority) {
case LOW -> 10;
case MEDIUM -> 15;
case HIGH -> 25;
};
}
}
enum Priority {
LOW,
MEDIUM,
HIGH
}Expected output after repair:
10
15
25The original printed 10 for MEDIUM because the final return 10; caught every
constant that was not HIGH. Adding one more if would fix MEDIUM but leave the
same trap for the next constant. The switch with no default turns that trap into
a compile error: add URGENT and the compiler reports that the switch does not
cover all possible input values.
Change it and test again
Rewrite Priority so each constant carries its minutes, as in LOW(10), and
replace the switch with a call to priority.minutes(). Then add URGENT with
no value. What does the compiler ask for now, and where? (It reports an error on
the URGENT line itself, constructor Priority in enum Priority cannot be applied to given types, because every constant must pass the minutes the constructor
requires. No caller needs to change.) Compare the two designs: which one
would you choose if a second method needed a different value per priority?
Explain before moving on
When would a string be a better choice than an enum? Explain why enum constants prevent spelling errors in source code but do not automatically validate text read from a user.
Completion is saved in this browser only. It does not measure mastery.