September 13, 2024
New Switch-Expressions in JAVA !
Java introduced Switch Expressions in Java 12 as a preview feature and fully implemented it in Java 14. This enhancement modernizes the…

By Rohit Kumar
2 min read
Java introduced Switch Expressions in Java 12 as a preview feature and fully implemented it in Java 14. This enhancement modernizes the traditional switch statement, making it more powerful, concise, and flexible. Switch expressions can now be used both as a statement and as an expression, allowing for more intuitive and concise code.
1. What Are Switch Expressions?
In traditional switch statements, developers often had to rely on break to prevent fall-through and use return statements to capture the result. Switch expressions eliminate this need, providing a cleaner, more readable way to write switch logic. They can return values, making them more versatile than the old switch.
Old Switch Statement (before Java 12):
int day = 5;
String dayName;
switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
// other cases
default:
dayName = "Invalid day";
}int day = 5;
String dayName;
switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
// other cases
default:
dayName = "Invalid day";
}New Switch Expression (Java 12+):
int day = 5;
String dayName = switch (day) {
case 1 -> "Sunday";
case 2 -> "Monday";
default -> "Invalid day";
};int day = 5;
String dayName = switch (day) {
case 1 -> "Sunday";
case 2 -> "Monday";
default -> "Invalid day";
};2. Key Features of Switch Expressions
a. Arrow Syntax (->)
The arrow (->) syntax simplifies the structure, eliminating the need for break statements. Each case directly leads to its result, making code more readable.
Example:
int number = 4;
String message = switch (number) {
case 1 -> "One";
case 2 -> "Two";
case 3 -> "Three";
default -> "Unknown number";
};int number = 4;
String message = switch (number) {
case 1 -> "One";
case 2 -> "Two";
case 3 -> "Three";
default -> "Unknown number";
};b. Switch as an Expression
Switch can now return a value, making it more versatile and useful when you need to assign the result directly to a variable.
Example:
int month = 3;
String season = switch (month) {
case 12, 1, 2 -> "Winter";
case 3, 4, 5 -> "Spring";
case 6, 7, 8 -> "Summer";
case 9, 10, 11 -> "Fall";
default -> "Unknown";
};int month = 3;
String season = switch (month) {
case 12, 1, 2 -> "Winter";
case 3, 4, 5 -> "Spring";
case 6, 7, 8 -> "Summer";
case 9, 10, 11 -> "Fall";
default -> "Unknown";
};c. Multiple Labels in One Case
You can now use multiple labels (case values) in one switch expression, separated by commas. This makes the code much cleaner.
Example:
String result = switch (grade) {
case "A", "B" -> "Good";
case "C" -> "Average";
case "D", "E" -> "Poor";
default -> "Fail";
};String result = switch (grade) {
case "A", "B" -> "Good";
case "C" -> "Average";
case "D", "E" -> "Poor";
default -> "Fail";
};d. yield Keyword
In cases where more complex logic is needed, you can use the yield keyword to return values in a switch expression. This allows for multi-line blocks within a case.
Example:
int score = 85;
String grade = switch (score / 10) {
case 9, 10 -> "A";
case 8 -> {
System.out.println("Good job!");
yield "B";
}
default -> "F";
};int score = 85;
String grade = switch (score / 10) {
case 9, 10 -> "A";
case 8 -> {
System.out.println("Good job!");
yield "B";
}
default -> "F";
};The yield keyword is necessary when the logic within a case block spans multiple lines or involves conditional logic.
3. Advantages of Switch Expressions
- Concise Code: Switch expressions reduce boilerplate code and make switch statements more readable and intuitive.
- Type-Safe: They ensure that a value is returned for every possible case, eliminating the risk of falling through cases.
- Return Values: Unlike traditional switch statements, switch expressions can return values, making them more flexible and practical.
- Enhanced Readability: With arrow syntax and support for multiple labels, the switch structure is cleaner and easier to understand.
4. Switch Expression vs. Traditional Switch Statement
5. Common Use Cases
Switch expressions are perfect for:
- Simplifying enum-based logic.
- Handling multiple related values like status codes or categories.
- Returning values based on logic where a concise decision-making structure is necessary.
Example:
DayOfWeek dayOfWeek = DayOfWeek.WEDNESDAY;
String typeOfDay = switch (dayOfWeek) {
case MONDAY, FRIDAY -> "Start or end of the work week";
case TUESDAY, WEDNESDAY, THURSDAY -> "Midweek";
case SATURDAY, SUNDAY -> "Weekend";
};DayOfWeek dayOfWeek = DayOfWeek.WEDNESDAY;
String typeOfDay = switch (dayOfWeek) {
case MONDAY, FRIDAY -> "Start or end of the work week";
case TUESDAY, WEDNESDAY, THURSDAY -> "Midweek";
case SATURDAY, SUNDAY -> "Weekend";
};Conclusion
Switch expressions in Java are a powerful enhancement over the traditional switch statement, offering cleaner syntax, better readability, and the ability to return values. By utilizing the arrow syntax, multiple case labels, and yield, developers can write more concise, flexible, and error-free code. This feature is especially beneficial for scenarios requiring decision-making logic with multiple conditions and values.
Java 8-to-Java 22 => Summary & Details of all new features !