Java ยท Chapter 14 of 42
Java Switch
The switch statement selects one of many code blocks to execute based on a variable's value. It is often cleaner than a long chain of else if statements.
Modern Java (14+) supports switch expressions with arrow syntax (->) that avoid fall-through bugs and can directly return a value.
Syntax
switch (value) {
case 1 -> System.out.println("one");
default -> System.out.println("other");
}Classic switch
Traditional switch uses case labels and break statements; forgetting break causes fall-through to the next case.
Switch expressions
Since Java 14, `switch` can be used as an expression with -> syntax, removing the need for break and allowing it to return a value directly.
Example 1 (java)
public class Main {
public static void main(String[] args) {
int day = 3;
String name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Unknown";
};
System.out.println(name);
}
}Output
WednesdayThe switch expression matches day == 3 and assigns "Wednesday" to name.
Key points
- switch selects a block based on a value.
- Classic switch needs break to prevent fall-through.
- Modern switch expressions use -> and can return a value.
- default handles unmatched cases.
๐ก Note: Prefer arrow-style switch expressions in modern Java to avoid fall-through bugs.
