Java - Switch Expressions in Modern Java
Switch expressions are an improved form of the traditional switch statement introduced in Java 14 as a standard feature. They make it easier to select one value from multiple possibilities and, importantly, allow a switch construct to return a value.
Traditional switch statements are mainly used to execute different blocks of code. Modern switch expressions can be used directly as part of an assignment or return statement.
1. Traditional Switch Statement
In older Java versions, a switch statement commonly looks like this:
int day = 2;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Invalid day";
}
Here, the switch statement does not directly produce a value. We need to declare dayName separately and assign a value inside each case.
The break statement is also important because it prevents execution from continuing into the next case.
2. Switch Expression
A modern switch expression can directly produce a value.
int day = 2;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Invalid day";
};
In this example, the switch expression evaluates the value of day and produces the corresponding string.
For example:
day = 1 → Monday
day = 2 → Tuesday
day = 3 → Wednesday
day = 5 → Invalid day
The resulting value is assigned directly to dayName.
3. Arrow Syntax
One of the most important improvements in modern switch expressions is the use of the arrow operator ->.
String result = switch (number) {
case 1 -> "One";
case 2 -> "Two";
case 3 -> "Three";
default -> "Other";
};
With arrow syntax, there is no need to use break.
The statement on the right side of -> is executed when that case matches.
This helps avoid accidental fall-through, which was a common source of errors with traditional switch statements.
4. Difference Between Colon and Arrow Syntax
Traditional syntax uses a colon:
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
}
Modern syntax can use an arrow:
switch (day) {
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
}
The arrow syntax is generally shorter and safer because one case does not automatically continue into the next case.
5. Multiple Case Labels
Multiple values can be handled by a single case using commas.
int day = 6;
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};
Here, days 1 through 5 are treated as weekdays, while 6 and 7 are treated as weekends.
This is more concise than writing separate cases for every value.
6. Switch Expressions with Blocks
Sometimes a case needs to perform several operations before producing a value. In that situation, a block can be used.
int marks = 85;
String grade = switch (marks / 10) {
case 10, 9 -> "A";
case 8 -> "B";
case 7 -> "C";
case 6 -> "D";
default -> "F";
};
A more complex case can contain multiple statements:
int number = 5;
String result = switch (number) {
case 1 -> "One";
case 5 -> {
System.out.println("Number is five");
yield "Five";
}
default -> "Other";
};
The yield keyword is used when a block-based switch expression needs to produce a value.
7. Understanding the yield Keyword
The yield keyword is specifically useful when a switch expression contains a block containing multiple statements.
Example:
int number = 10;
String result = switch (number) {
case 10 -> {
int value = number * 2;
yield "Result: " + value;
}
default -> {
yield "Other number";
}
};
System.out.println(result);
Output:
Result: 20
Here, yield returns the value from the switch expression.
It is important to distinguish yield from return.
return exits a method, whereas yield provides the result of a switch expression.
8. Switch Expressions with Characters
Switch expressions can also work with characters.
char grade = 'A';
String message = switch (grade) {
case 'A' -> "Excellent";
case 'B' -> "Good";
case 'C' -> "Average";
case 'D' -> "Pass";
default -> "Invalid grade";
};
System.out.println(message);
Output:
Excellent
9. Switch Expressions with Strings
Strings can also be used in switch expressions.
String month = "January";
int days = switch (month) {
case "January", "March", "May", "July",
"August", "October", "December" -> 31;
case "April", "June", "September", "November" -> 30;
case "February" -> 28;
default -> 0;
};
System.out.println(days);
Output:
31
This makes switch expressions useful for menu systems, categories, commands, grades, status values, and many other applications.
10. Default Case
A default case handles values that do not match any of the explicitly defined cases.
int option = 5;
String message = switch (option) {
case 1 -> "Add";
case 2 -> "Edit";
case 3 -> "Delete";
default -> "Invalid option";
};
Since 5 does not match cases 1, 2, or 3, the default case executes.
For a switch expression, providing a default case is particularly important when the possible input values are not otherwise completely covered.
11. Switch Statement vs Switch Expression
The main difference is that a switch statement performs actions, while a switch expression produces a value.
Traditional switch:
switch (choice) {
case 1:
System.out.println("Add");
break;
case 2:
System.out.println("Delete");
break;
}
Switch expression:
String action = switch (choice) {
case 1 -> "Add";
case 2 -> "Delete";
default -> "Unknown";
};
The second version can be directly used in an assignment because it produces a value.
12. Advantages of Switch Expressions
Switch expressions provide several benefits.
Simpler code: They reduce the amount of code required for straightforward selection logic.
No unnecessary break: Arrow syntax eliminates the need for break after each case.
Reduced fall-through errors: Each arrow case normally handles only its own result.
Direct value assignment: The result can be assigned directly to a variable.
Better readability: The relationship between an input and its resulting value is easier to understand.
Useful for conditional calculations: They can replace many situations where a variable would otherwise have to be assigned inside different cases.
13. Practical Example
Consider a simple application that converts a numeric menu choice into an operation:
int choice = 2;
String operation = switch (choice) {
case 1 -> "Create new record";
case 2 -> "Update record";
case 3 -> "Delete record";
case 4 -> "View record";
default -> "Invalid choice";
};
System.out.println(operation);
Output:
Update record
The switch expression determines the appropriate text and assigns it directly to operation.
14. Important Points to Remember
When working with modern Java switch expressions, remember the following:
-
A switch expression produces a value.
-
It can be assigned to a variable.
-
Arrow syntax uses
->. -
Arrow-style cases do not require
break. -
Multiple case values can be separated by commas.
-
A block can be used when a case requires multiple statements.
-
yieldis used to provide a value from a block inside a switch expression. -
defaultcan handle unmatched values. -
Switch expressions can work with supported types such as integers, characters, strings, and enums.
-
Switch expressions make selection-based code shorter, clearer, and less prone to fall-through errors.
Conclusion
Switch expressions are an important improvement in modern Java because they allow a switch construct to produce a value directly. The arrow syntax removes much of the boilerplate associated with traditional switch statements, while yield provides a way to return a value from more complex case blocks. They are particularly useful when a program needs to choose one result from several possible values, making the code easier to read and maintain.