switch as an Expression
Return values from switch.
Statements vs Expressions
A statement performs an action. An expression produces a value. Modern Java lets switch be an expression, so you can assign its result directly to a variable.
Assigning a switch Result
When switch appears on the right side of =, each branch supplies the value. The arrow form returns the value after -> automatically.
public class Main {
public static void main(String[] args) {
int day = 6;
String type = switch (day) {
case 6, 7 -> "Weekend";
default -> "Weekday";
};
System.out.println(type);
}
}All lessons in this course
- Arrow-Style switch
- switch as an Expression
- The yield Keyword
- Multi-Label Cases