Switch Expressions in Java
Learn Java switch expressions, arrow labels, yield, enum exhaustiveness, and how the Java 21 pattern-matching switch differs.
Learn Java switch expressions, arrow labels, yield, enum exhaustiveness, and how the Java 21 pattern-matching switch differs.
Switch Expressions in Java
Switch expressions let a switch produce a value. They were previewed in Java 12 and 13, then became a standard feature in Java 14 (JEP 361).
Introduction
Switch expressions were previewed in Java 12 and 13 and became standard in Java 14. They evaluate to a value, so you can return or assign the result directly. The arrow label form (case ... ->) avoids fall-through and works in switch statements as well as switch expressions. Traditional colon labels remain available and can fall through.
Every switch expression must be exhaustive. For an int, that usually means adding a default branch. For an enum, you can list every constant and omit default, allowing the compiler to flag a newly added constant when the code is recompiled. The Java 21 pattern-matching switch is a separate feature: it was previewed in Java 17–20 and became standard in Java 21 (JEP 441).
This post covers switch expressions, arrow labels, yield, enum exhaustiveness, and the Java 21 pattern-matching switch.
When to Use / Not to Use
Use switch expressions when:
- Selecting from multiple discrete values based on a single expression
- Mapping input to output values (functional style)
- Replacing simple if-else-if chains with mutually exclusive cases
- Working with enum-based branching
Do not use switch expressions when:
- Conditions span ranges—use if-else with comparisons
- Complex conditions involving multiple variables—use if-else
- Only two branches—use simple if-else or ternary operator
- Fall-through behavior is needed (use colon labels in a switch statement)
Diagram: Switch Expression Flow
flowchart TD
A["switch (expression)"] --> B{"Match Case?"}
B -->|case A| C["yield valueA"]
B -->|case B| D["yield valueB"]
B -->|case C| E["yield valueC"]
B -->|default| F["yield defaultValue"]
C --> G["Result = valueA"]
D --> G
E --> G
F --> G
G --> H["Continue"]
Code Snippet: Switch Statements and Expressions
public class SwitchExpressionDemo {
// Traditional switch statement with colon labels
public static String getDayTypeOld(int day) {
String result;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
result = "Weekday";
break;
case 6:
case 7:
result = "Weekend";
break;
default:
result = "Invalid";
}
return result;
}
// Switch expression (standard since Java 14)
public static String getDayTypeNew(int day) {
return switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};
}
// Switch expression with blocks (using yield)
public static String getDayDescription(int day) {
return switch (day) {
case 1, 2, 3, 4, 5 -> {
String desc = "Work day";
yield desc + " (Monday-Friday)";
}
case 6 -> "Saturday - rest day";
case 7 -> "Sunday - rest day";
default -> throw new IllegalArgumentException("day must be between 1 and 7: " + day);
};
}
// Pattern matching for switch (standard since Java 21)
public static String describe(Object obj) {
return switch (obj) {
case Integer i when i > 0 -> "Positive integer: " + i;
case Integer i -> "Non-positive integer: " + i;
case String s -> "String of length " + s.length();
case null -> "Null value";
default -> "Something else: " + obj.getClass().getSimpleName();
};
}
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
// No default is needed when every enum constant is covered.
public static int lettersInDay(Day day) {
return switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
};
}
public static void main(String[] args) {
// Basic usage
System.out.println(getDayTypeNew(3)); // Weekday
System.out.println(getDayTypeNew(7)); // Weekend
System.out.println(lettersInDay(Day.WEDNESDAY)); // 9
try {
getDayDescription(8);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage()); // day must be between 1 and 7: 8
}
// Pattern matching examples
System.out.println(describe(42)); // Positive integer: 42
System.out.println(describe(-5)); // Non-positive integer: -5
System.out.println(describe("hello")); // String of length 5
System.out.println(describe(null)); // Null value
System.out.println(describe(3.14)); // Something else: Double
}
}
Exhaustiveness and Invalid Input
Switch expressions have to produce a value on every path. A switch over an arbitrary int therefore needs a default or cases covering every possible value, which is impractical; decide explicitly how out-of-range input should behave. The getDayDescription example throws IllegalArgumentException for values outside 1–7.
An enum expression can omit default when all declared constants are listed. If a new constant is added, recompiling the switch can reveal the missing case. A default branch in this situation can hide that useful compiler warning. Classic switch statements do not generally have the same exhaustiveness requirement and can do nothing when no label matches.
For a block-bodied switch-expression rule, use yield to provide its value. A switch expression cannot complete normally without a value; it can instead throw an exception.
Trade-off Table
| Feature | Switch Statement | Switch Expression |
|---|---|---|
| Returns value | No | Yes |
| Arrow labels | Yes, standard since Java 14 | Yes, standard since Java 14 |
| Block value | No yield |
yield provides a value from a block |
| Patterns | Java 21; previewed in Java 17–20 | Java 21; previewed in Java 17–20 |
| Exhaustiveness | Not generally required | Required; enum cases may omit default when all constants are listed |
| Fall-through | Possible with : labels; arrows do not fall through |
Possible with : labels; arrows do not fall through |
Observability Checklist
- Log switch input values and matched cases for debugging
- Add metrics for case frequency distribution
- Instrument default case hits (may indicate unexpected input)
- Add integration tests for all case branches
- Monitor for unhandled case patterns in production
Security Notes
- Input validation: An
intswitch does not validate a domain such as 1–7 by itself; give invalid values an explicit result or throw an exception. - Enum safety: Cover every enum constant and omit
defaultwhen you want recompilation to identify newly added constants. - Null handling: Before Java 21, a null selector throws
NullPointerException. In a Java 21 pattern-matching switch, usecase nullwhen null should be handled explicitly.
Pitfalls
- Forgetting
yield: A block in a switch expression needs to yield a value or throw. - Adding
defaultto every enum expression: When all constants are already covered, omitting it can expose newly added constants on recompilation. - Mixing
:and->labels: A switch block uses one label style, not both. - Assuming every switch statement is exhaustive: A classic statement can silently do nothing when no label matches.
- Assuming
case nullworks in Java 14: It became available with Java 21’s pattern-matching switch; earlier switch selectors throwNullPointerExceptionfor null.
Quick Recap
- Switch expressions became standard in Java 14; arrow labels also work in switch statements.
- Use
yieldto provide a value from a block in a switch expression. - Multiple values can be comma-separated in one case:
case 1, 2, 3 -> - Switch expressions must be exhaustive. An enum expression can omit
defaultwhen every constant is listed. - Pattern matching and
case nullin switch became standard in Java 21.
Interview Questions
- If-Else Statements in Java - When if-else is more appropriate than switch
- Ternary Operator - Simple binary value selection vs switch
- Pattern Matching in Java - Advanced pattern matching with sealed classes
- Java Enums and Switch - Using switch with enum types effectively
- Switch Expressions and Statements (Java 21) - Arrow labels,
yield, and exhaustiveness - Java Language Changes Summary - Permanent and preview language features by release
- Pattern Matching with switch (Java 27) - Type patterns and guarded labels
- JEP 441 - Pattern matching for switch in Java 21
Conclusion
Switch expressions modernize Java’s branching by treating switch as an expression that returns values rather than just a statement that executes code. The arrow syntax -> and yield keyword eliminate the traditional fall-through bug, and exhaustive checking at compile time prevents runtime surprises.
Pattern matching in switch (Java 21+) takes this further by matching on types directly, eliminating chains of instanceof checks. For most multi-way branching scenarios, switch expressions are cleaner than if-else chains and more maintainable than scattered conditionals.
Switch expressions became standard in Java 14. Arrow labels can also simplify switch statements, while pattern matching and case null arrived later as part of Java 21. For enum expressions, listing every constant without default leaves the compiler able to flag a missing case after the enum changes. Use a default for open-ended inputs such as arbitrary integers, and decide explicitly how invalid values should behave.
The ternary operator remains useful for simple binary choices, while if-else statements handle ranges and complex conditions.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.