Sub topic 2
Switching on Enums
You often need to do something different for each enum constant. For example, a program might print "Weekend!" on Saturday and "Work day." on Monday. Java has a tool built for this. It is called switch.
A switch is a statement that looks at one value and jumps to the branch that matches it. Enums and switch fit together well. An enum has a fixed list of constants, so the compiler knows every value the switch might see.
This chapter uses the Day enum from the previous chapter:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }You will learn three forms of switch:
- The classic switch statement with colons and
break. - The arrow switch statement, which is shorter and safer.
- The switch expression, which produces a value and can be checked for completeness.
The Classic Switch Statement
The oldest form of switch uses case LABEL: followed by code. Here is a full program you can run.
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class OldSwitch {
public static void main(String[] args) {
Day today = Day.SATURDAY;
switch (today) {
case SATURDAY:
case SUNDAY:
System.out.println("Weekend!");
break;
default:
System.out.println("Work day.");
break;
}
}
}Save it as OldSwitch.java. Run it with java OldSwitch.java. It prints Weekend!.
Here is what each part does:
switch (today)picks the value to test. This value is called the selector.case SATURDAY:is a case label. A case label is a value the switch compares against the selector.breakends the switch. Without it, Java keeps running into the next case.default:runs when no case label matches.
Notice that the labels say SATURDAY, not Day.SATURDAY. The switch already knows the selector is a Day, so you write the plain constant name.
The Fall-Through Trap
Two labels in a row, case SATURDAY: and case SUNDAY:, share the same code. This works because of fall-through. Fall-through means that once a case matches, Java runs every line below it until it hits a break or the end of the switch.
Fall-through helps when you group labels. It hurts when you forget a break. Look at this program:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class FallThroughBug {
public static void main(String[] args) {
Day today = Day.FRIDAY;
switch (today) {
case FRIDAY:
System.out.println("Almost the weekend.");
case SATURDAY:
System.out.println("Weekend!");
break;
default:
System.out.println("Work day.");
}
}
}It prints two lines:
Almost the weekend.
Weekend!The FRIDAY case has no break, so Java falls into the SATURDAY code. This is a common bug. The compiler does not warn you about it.
The Arrow Switch Statement
Java 14 added a cleaner form. You write case LABEL -> instead of case LABEL:. An arrow case runs only its own code. It never falls through, so you do not need break.
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class ArrowSwitch {
public static void main(String[] args) {
for (Day day : Day.values()) {
switch (day) {
case SATURDAY, SUNDAY -> System.out.println(day + ": Weekend!");
case FRIDAY -> System.out.println(day + ": Almost the weekend.");
default -> System.out.println(day + ": Work day.");
}
}
}
}This prints one line for each day. Two things are new:
case SATURDAY, SUNDAY ->lists several labels in one case, separated by commas. This replaces the old trick of stacking labels.- Each arrow points to a single statement. If you need several statements, wrap them in braces:
case FRIDAY -> { ... }.
You cannot mix : cases and -> cases in the same switch. Pick one style per switch.
Switch Expressions
So far, each switch has done something, such as printing. Often you want a switch to produce a value instead. A switch expression is a switch that gives back a result, so you can store it in a variable or return it.
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class SwitchExpression {
static boolean isWeekend(Day day) {
return switch (day) {
case SATURDAY, SUNDAY -> true;
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> false;
};
}
public static void main(String[] args) {
System.out.println(isWeekend(Day.SUNDAY)); // true
System.out.println(isWeekend(Day.MONDAY)); // false
}
}Look closely at the switch:
- It comes after
return, so its result is returned. - Each arrow points to a value (
trueorfalse), not to a statement. - It ends with a semicolon
};, because the whole switch is part of thereturnstatement. - It has no
default.
Exhaustiveness
A switch expression must always produce a value. So the compiler checks that every possible selector value has a case. A switch that covers every possible value is called exhaustive.
For an enum, the compiler knows the full list of constants. Our isWeekend switch lists all seven days, so it is exhaustive. No default is needed.
If you leave out a day, the program will not compile. Try deleting FRIDAY from the second case. The compiler stops with an error like this:
error: the switch expression does not cover all possible input valuesThis error is useful. It catches a missing case before your program ever runs.
Why Skipping default Is Often Better
You could make any switch expression compile by adding default -> false;. But think about what happens later. Suppose someone adds a new constant to the enum:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY, HOLIDAY }- Without
default:isWeekendno longer compiles. The compiler points you to the exact place you must decide whatHOLIDAYmeans. - With
default: everything compiles.HOLIDAYquietly returnsfalse. Nobody is told, and that may be wrong.
A default still makes sense when most constants share one answer and new constants should get that answer too. Choose on purpose.
Blocks and yield
Sometimes a case needs more than one line to work out its value. You can use a block in braces. Inside the block, the keyword yield gives the value for that case. yield means "this is the result of the switch for this case."
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class YieldDemo {
static int workHours(Day day) {
return switch (day) {
case SATURDAY, SUNDAY -> 0;
case FRIDAY -> {
System.out.println("Short day on Friday.");
yield 6;
}
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY -> 8;
};
}
public static void main(String[] args) {
int total = 0;
for (Day d : Day.values()) {
total += workHours(d);
}
System.out.println("Total hours: " + total);
}
}This prints Short day on Friday. and then Total hours: 38. In a switch expression, use yield inside a block, not return. A return there would try to leave the whole method, and the compiler does not allow that.
Switch Statements Do Not Have to Be Complete
The completeness check applies to switch expressions. A plain switch statement over an enum, in either the colon form or the arrow form, may skip constants. If nothing matches, it does nothing.
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class PartialSwitch {
public static void main(String[] args) {
Day today = Day.TUESDAY;
switch (today) {
case MONDAY -> System.out.println("Team meeting at 9.");
case FRIDAY -> System.out.println("Demo day.");
}
System.out.println("Done.");
}
}This prints only Done.. No case matched TUESDAY, and that is allowed. Watch for this: a statement will not warn you about a missing case.
Watch Out for null
An enum variable can hold null, which means "no constant at all." If the selector is null, the switch throws a NullPointerException. This happens in every form shown in this chapter, even when a default is present.
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class NullSwitch {
public static void main(String[] args) {
Day today = null;
try {
switch (today) {
case SATURDAY, SUNDAY -> System.out.println("Weekend!");
default -> System.out.println("Work day.");
}
} catch (NullPointerException e) {
System.out.println("The day was null.");
}
}
}This prints The day was null.. The safest habit is to make sure enum variables never hold null. Java 21 also lets you write a case null -> branch. You will see more of that in the chapter on pattern matching.
Comparing the Forms
| Form | Syntax | Falls through? | Produces a value? | Must cover all constants? |
|---|---|---|---|---|
| Classic statement | `case X:` with `break` | Yes, unless you `break` | No | No |
| Arrow statement | `case X ->` | No | No | No |
| Switch expression | `case X ->` with a value, or `yield` | No | Yes | Yes |
The diagram below shows how to pick a form.
For new code, prefer the arrow form. Use a switch expression whenever the switch's job is to compute a value.
Exercise
Write a method static String mood(Day day) that uses a switch expression with no default. It should return "tired" for MONDAY, "happy" for FRIDAY, SATURDAY, and SUNDAY, and "okay" for every other day. Then explain what happens if you delete the TUESDAY label.
Show answer
static String mood(Day day) { return switch (day) { case MONDAY -> "tired"; case FRIDAY, SATURDAY, SUNDAY -> "happy"; case TUESDAY, WEDNESDAY, THURSDAY -> "okay"; }; } If you delete TUESDAY, the code stops compiling. The switch expression no longer covers every constant, so the compiler reports that it "does not cover all possible input values."
Exercise
A classic switch has case MONDAY: System.out.println("Start"); case TUESDAY: System.out.println("Keep going"); break;. What does it print when the selector is MONDAY, and how would you fix it with the arrow form?
Show answer
It prints "Start" and then "Keep going", because MONDAY has no break and falls through into TUESDAY. With the arrow form there is no fall-through: case MONDAY -> System.out.println("Start"); case TUESDAY -> System.out.println("Keep going"); prints only "Start" for MONDAY.
Exercise
Inside a switch expression, a case uses a block { ... }. Which keyword gives that case's value, and why can't you use return there?
Show answer
Use yield, for example yield 6;. A return would try to leave the whole surrounding method instead of giving the switch its value, so the compiler rejects it inside a switch expression.