Control Structures
Completion requirements
2. Switch Statement
2.1. Notes:
The break statement prevents fall-through to subsequent cases. Without break, all cases after a match are executed.
The default case is optional and executes if no case matches.
Java 12+ Switch Expressions (enhanced switch):
public class SwitchExpression {
public static void main(String[] args) {
String day = "Monday";
String result = switch (day) {
case "Monday" -> "Start of the week";
case "Friday" -> "End of the work week";
default -> "Midweek or weekend";
};
System.out.println(result); // Output: Start of the week
}
}
Uses -> for concise syntax and no break needed.
Can assign the result directly to a variable.