The switch expression, introduced in Java 12 (as a preview feature) and became a standard feature in Java 14, provides a more concise and powerful way to use switch statements. Here’s how to use it effectively:
Key Features of Switch Expressions
- Simpler Syntax: The new syntax allows the use of the
->syntax to eliminate fall-through behavior. - Expression Form: The
switchcan now return a value directly. - Multiple Labels: Multiple case labels can share the same logic using a comma-separated list.
- No More Breaks: No need for the
breakkeyword after each case.
Syntax for Switch Expressions
Here’s a quick breakdown:
String dayType = switch (dayOfWeek) {
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Weekday";
case "Saturday", "Sunday" -> "Weekend";
default -> throw new IllegalArgumentException("Invalid day: " + dayOfWeek);
};
Explanation:
- The
->syntax replaces the colon andbreakof the traditionalswitch. defaultacts as a fallback for unmatched cases.- The result of the
switchis assigned directly to the variabledayType. - Multiple cases separated by commas handle identical conditions.
Examples of Switch Expressions
Return a Value Directly from switch
int month = 3;
int daysInMonth = switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9, 11 -> 30;
case 2 -> 28; // Use 29 for leap years, this is simplified.
default -> throw new IllegalArgumentException("Invalid month: " + month);
};
System.out.println("Days in Month: " + daysInMonth);
Using Code Blocks in a Case
For more complex logic, you can use curly braces {} to group multiple statements into a block. In such cases, you must use the yield keyword to specify a value to be returned.
String grade = "B";
String feedback = switch (grade) {
case "A", "B" -> "Great job!";
case "C", "D" -> {
System.out.println("Encouraging message for grade: " + grade);
yield "Needs improvement.";
}
case "F" -> "Failed.";
default -> throw new IllegalArgumentException("Unknown grade: " + grade);
};
System.out.println("Feedback: " + feedback);
Advantages Over Traditional switch
- No Fall-Through: Avoid accidentally executing multiple cases (common bug with traditional
switch). - Cleaner Syntax: Easier to read and write due to the arrow operator (
->) and elimination ofbreak. - Enhanced Type Safety: The returned value must match the expected type assigned to the variable.
- Pattern Matching (Java 17+): Future extensions allow
switchwith pattern matching for richer capabilities.
Use Cases
- Assigning values directly with clear logic.
- Simplifying code structure for multiple conditions or enums.
- Handling complex branching logic.
