Starting in Java , a switch can be an expression that produces a value. You assign the result directly to a variable.
int day = 5;
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};
Notice the semicolon after the closing brace. The entire switch is a single expression that evaluates to a String.
When a case needs multiple statements, use the yield keyword to return the value:
String label = switch (day) {
case 1 -> {
System.out.println("Processing...");
yield "Monday";
}
default -> "Other";
};
The compiler forces every possible input to be covered. If you switch on an int and don't list all cases, you must include a default. Missing coverage causes a compile error, which protects you from forgetting a case.