Introduction
Java 12 introduced switch expressions as a preview feature, which aimed to simplify and extend the traditional switch
statement. This enhancement provides a more concise syntax and allows switch
to be used as an expression that returns a value. Switch expressions were further enhanced and standardized in Java 13 and became a permanent feature in Java 14.
Key Points:
- Concise Syntax: Reduces boilerplate code and improves readability.
- Returns a Value: Allows the
switch
to be used as an expression that returns a value. - Arrow Syntax: Provides a more readable arrow syntax (
->
) for case branches. - Multiple Labels: Supports multiple labels for a single case.
- Exhaustiveness: Ensures all possible input values are covered, leading to more robust code.
Traditional switch Statement
Before diving into switch expressions, let’s review the traditional switch
statement and its limitations.
Example: Traditional switch Statement
public class TraditionalSwitchExample {
public static void main(String[] args) {
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("Day: " + dayName);
}
}
Output:
Day: Tuesday
Limitations:
- Verbose Syntax: The traditional
switch
statement requires a lot of boilerplate code, including the use ofbreak
statements to prevent fall-through. - Not an Expression: It cannot directly return a value; you must manually assign a value within each case.
- Fall-Through: Forgetting a
break
statement can lead to unintended fall-through behavior.
Switch Expressions
Switch expressions address these limitations by providing a more concise and expressive syntax. They allow switch
to be used as an expression that returns a value, enabling direct assignment to variables.
Syntax
String result = switch (variable) {
case value1 -> expression1;
case value2 -> expression2;
case value3, value4 -> expression3;
default -> expression4;
};
- Arrow (
->
): Indicates the result for each case. - Multiple Labels: Allows multiple labels to be specified for a single case.
- Expression Value: The value of the
switch
expression is the result of the matched case.
Example: Switch Expression
Let’s rewrite the previous example using a switch expression.
public class SwitchExpressionExample {
public static void main(String[] args) {
int day = 3;
// Use a switch expression to get the day name
String dayName = switch (day) {
case 1 -> "Sunday";
case 2 -> "Monday";
case 3 -> "Tuesday";
case 4 -> "Wednesday";
case 5 -> "Thursday";
case 6 -> "Friday";
case 7 -> "Saturday";
default -> "Invalid day";
};
System.out.println("Day: " + dayName);
}
}
Output:
Day: Tuesday
Explanation:
- Concise Syntax: The switch expression eliminates the need for
break
statements, reducing boilerplate code. - Expression Value: The result of the matched case is directly returned and assigned to the
dayName
variable.
Enhanced Switch Expressions
Switch expressions in Java 14 and later include additional features like the yield
statement and block-based case expressions.
Using yield in Switch Expressions
The yield
statement allows you to return a value from a block-based switch expression case, providing greater flexibility.
Example: Using yield
public class YieldExample {
public static void main(String[] args) {
int day = 5;
// Use a switch expression with block-based cases
String dayType = switch (day) {
case 1, 7 -> "Weekend";
case 2, 3, 4, 5, 6 -> "Weekday";
default -> {
yield "Invalid day";
}
};
System.out.println("Day Type: " + dayType);
}
}
Output:
Day Type: Weekday
Explanation:
- Block-Based Cases: You can use block-based cases to execute multiple statements and use
yield
to return a value. - Multiple Labels: Cases can have multiple labels, making it easier to group related cases.
Switch Expressions with Enums
Switch expressions work seamlessly with enums, providing a more readable and maintainable way to handle enum values.
Example: Switch Expression with Enums
public class EnumSwitchExample {
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public static void main(String[] args) {
Day day = Day.WEDNESDAY;
// Use a switch expression with an enum
String activity = switch (day) {
case SATURDAY, SUNDAY -> "Relax";
case MONDAY -> "Work hard";
case TUESDAY -> "Work hard";
case WEDNESDAY -> "Midweek work";
case THURSDAY -> "Almost there";
case FRIDAY -> "Finish work";
};
System.out.println("Activity: " + activity);
}
}
Output:
Activity: Midweek work
Explanation:
- Enums: Switch expressions can be used with enums, providing clear and concise handling of enum values.
- Exhaustiveness: All possible enum values are covered, ensuring comprehensive handling.
Benefits of Switch Expressions
- Conciseness: Reduces boilerplate code and improves readability.
- Safety: Eliminates fall-through behavior and ensures exhaustive case handling.
- Flexibility: Supports returning values directly from cases, making code more expressive.
- Compatibility: Works with both primitive values and enums.
Conclusion
Switch expressions in Java provide a powerful enhancement to the traditional switch
statement, allowing for more concise, flexible, and expressive code. By leveraging switch expressions, developers can simplify control flow logic and improve code readability.
Summary:
- Concise Syntax: Reduces boilerplate code and improves readability.
- Expression Value: Allows
switch
to be used as an expression that returns a value. - Enhanced Features: Supports multiple labels, block-based cases, and
yield
statements. - Exhaustiveness: Ensures all possible input values are covered, leading to more robust code.
By adopting switch expressions, you can enhance the quality and maintainability of your Java applications.