Lesson 5 of 23
In progress
switch and enums
Choose among fixed values with switch, use the arrow form that cannot fall through, and let an enum make the set of values explicit.
switch answers a narrower question than if: which of these known values is it? That constraint is what makes it readable, and the arrow form makes it safe.
What you will learn
- Write a classic
switchand avoid fall-through. - Use the arrow form and
switchexpressions. - Model a fixed set of values with an enum.
The classic form
public class Menu {
public static void main(String[] args) {
int choice = 2;
switch (choice) {
case 1:
System.out.println("New file");
break;
case 2:
System.out.println("Open file");
break;
case 3:
System.out.println("Save");
break;
default:
System.out.println("Unknown choice");
}
}
}
Each case ends with break, which exits the switch. Without it, execution continues into the next case — fall-through — which is occasionally intended and usually a bug.
Allowed switch types are integers, char, String, enums and a few wrapper types. double and boolean are not allowed, because exact matching on those values is either meaningless or already covered by if.
Fall-through on purpose
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weekday");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Not a day");
}
Stacked empty cases group values, and that is the only fall-through worth writing. Any other kind needs a comment, because a reader assumes it is a mistake.
The arrow form
switch (day) {
case 1, 2, 3, 4, 5 -> System.out.println("Weekday");
case 6, 7 -> System.out.println("Weekend");
default -> System.out.println("Not a day");
}
Arrow cases do not fall through, so no break is needed, and several values can share one case. This is the form to use in new code: it removes the most common bug in the statement.
switch as an expression
String label = switch (status) {
case "paid" -> "Paid";
case "pending" -> "Awaiting payment";
case "refunded" -> "Refunded";
default -> "Unknown";
};
A switch expression produces a value, which makes it usable in an assignment or a method call. With an enum and exhaustive cases, the default can be omitted and the compiler will check that every constant is covered.
For a block body, use yield:
int fee = switch (tier) {
case "basic" -> 0;
case "pro" -> {
int base = 9900;
yield base * 12;
}
default -> throw new IllegalArgumentException("Unknown tier: " + tier);
};
yield returns from the block. Throwing in the default is often better than a silent fallback: an unexpected value is a bug, and a wrong label hides it.
Enums
An enum is a fixed set of named values, and it is the right type for a status.
public enum OrderStatus {
PENDING, PAID, SHIPPED, CANCELLED
}
OrderStatus status = OrderStatus.PAID;
String label = switch (status) {
case PENDING -> "Awaiting payment";
case PAID -> "Paid";
case SHIPPED -> "On the way";
case CANCELLED -> "Cancelled";
};
Because every constant is covered, no default is needed. If someone adds a constant later, this switch stops compiling until it is handled — the compiler enforcing the rule you would otherwise forget.
An enum can also carry data and behaviour:
public enum Plan {
BASIC(0, 5),
PRO(9900, 50),
TEAM(24900, 500);
private final int monthlyPaise;
private final int seats;
Plan(int monthlyPaise, int seats) {
this.monthlyPaise = monthlyPaise;
this.seats = seats;
}
int monthlyPaise() { return monthlyPaise; }
int seats() { return seats; }
}
Plan.PRO.monthlyPaise() returns 9900, and the values cannot drift apart because they are defined together. That is a large improvement over a set of constants plus a parallel array.
When not to use switch
If the branches call different methods with different arguments, a chain of if is clearer than a switch that only selects a call. If there are two values, an if is shorter.
Switch shines when one value maps to a label, a small calculation, or a category. A switch that only picks which method to call is often a sign that the behaviour belongs on the enum constant itself, where it cannot be forgotten when a new value appears. Once the mapping grows to a table with several columns, a Map or a small class may express it better.
Strings in switch
Switching on a String is legal and uses equals semantics, with a NullPointerException if the value is null. Guard the null case before the switch, or switch on an enum parsed earlier.
if (input == null) {
throw new IllegalArgumentException("status is required");
}
Parsing text into an enum at the boundary — OrderStatus.valueOf(input.trim().toUpperCase()) — moves the risk to one place and lets the rest of the code switch on a closed set.
Writing a classic switch and forgetting one break. The case falls into the next one, two messages print, and the output looks almost right. The arrow form makes this impossible.
Write an enum for three ticket priorities and a switch expression that returns a response time in hours: 1 for urgent, 8 for normal, 48 for low. Print the result.
Show solution
public class Tickets { enum Priority { URGENT, NORMAL, LOW } public static void main(String[] args) { Priority p = Priority.NORMAL; int hours = switch (p) { case URGENT -> 1; case NORMAL -> 8; case LOW -> 48; }; System.out.println(p + " responds within " + hours + " hours"); } } The enum makes the set of values explicit, and the switch expression covers all three without a default. Adding a fourth priority would fail to compile until it is handled, which is the behaviour you want.
Recap
- Classic
switchneedsbreak; arrow cases cannot fall through and group values with commas. - A switch expression returns a value, with
yieldfor blocks. - Use an enum for a fixed set of states so the compiler checks completeness.
Next, for loops: counting, iterating arrays, and the two forms worth knowing.
Can switch match ranges?
Is switch on String slow?
Progress is saved in this browser only. No account, no email.