Switch Expressions
TL;DR
- Switch Expressions (finalized in Java 14) transform the traditional
switchstatement from a control flow structure into an expression that evaluates to a value. - They introduce the arrow syntax
->which eliminates the need forbreakstatements. - They allow multiple comma-separated labels per case.
Concept
The old C-style switch statement in Java was notoriously error-prone. If you forgot a break; statement, execution would “fall through” into the next case, causing terrible bugs. Additionally, using a switch to assign a value to a variable was incredibly clunky.
Switch Expressions fix both issues.
- Expressions: The switch block can now directly return a value (like a ternary operator), allowing you to assign the result directly to a variable:
int size = switch(day) { ... }. - Arrow Syntax: Using
case "Monday" ->completely disables fall-through. Only the code immediately to the right of the arrow is executed. Nobreakrequired!
Examples
public class SwitchDemo {
public enum Day { MONDAY, TUESDAY, FRIDAY, SATURDAY, SUNDAY }
public static void main(String[] args) {
Day today = Day.SATURDAY;
// 1. The Modern Switch Expression (Java 14+)
// Notice it evaluates to a String, which we assign directly.
String mood = switch (today) {
// Multiple labels in one case! No fall-through!
case MONDAY, TUESDAY -> "Sad";
case FRIDAY -> "Excited";
case SATURDAY, SUNDAY -> "Happy";
};
System.out.println("Mood: " + mood);
// 2. The 'yield' keyword
// If a case is complex and requires multiple lines of code, you use a block {}
// Inside the block, you use 'yield' (not 'return') to output the value for the switch.
int wordLength = switch ("Hello") {
case "Hi" -> 2;
case "Hello" -> {
System.out.println("Processing Hello...");
yield 5; // Outputs 5 to the wordLength variable
}
default -> 0; // Exhaustiveness requires a default case!
};
}
}
Interview Questions
Q: What does “Exhaustiveness” mean in a Switch Expression?
A: Because a Switch Expression must return a value, the compiler enforces that every possible input has a defined output. If you are switching on an int, you must provide a default case, because it’s impossible to write a case for all 4 billion integers. However, if you are switching on an Enum, and you write a case for every single enum constant, the compiler considers it exhaustive and you do not need a default case!
Q: Can you still use the colon : syntax in modern Java?
A: Yes. You can use the traditional case "A": syntax as a Switch Expression (by using yield instead of break), and you can use the new arrow case "A" -> syntax as a standard Switch Statement (where it doesn’t return a value). However, you cannot mix colons and arrows in the same switch block.