Switch Expression
A switch expression produces a value. Arrow cases do not fall through, and several labels can share one result.
Using a switch as an expression keeps the mapping next to the variable it initializes. The compiler also checks that every possible input has a result.
Weekday or weekend
public class Main {
public static void main(String[] args) {
int day = 7;
String dayType = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid day";
};
System.out.println(dayType);
}
}
Output:
Weekend
Saturday and Sunday use the same result, so cases 6 and 7 share Weekend. Any other value outside 1 through 7 uses Invalid day.
A block-shaped arrow case can perform extra work and use yield to supply its value, but a simple expression is easier when it fits.
Use a switch expression to describe a grade.