Lesson 11: Advanced Control Flow: The switch Statement
The switch statement is an alternative to long if-else if ladders when comparing a single variable against multiple potential constant values.
1. Traditional switch Syntax
Java uses case labels to define possible values and the break keyword to exit the structure.
java int dayOfWeek = 3; // Wednesday String dayName;
switch (dayOfWeek) { case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; default: dayName = "Unknown Day"; // No break needed here as it's the last case }
System.out.println(dayName); // Output: Wednesday
The break Keyword: Fall-through
If you omit the break statement, execution will 'fall through' to the next case, which is usually undesirable.
2. Modern Java switch Expressions (JDK 14+)
Modern Java introduced switch expressions using the arrow (->) notation, which automatically handles the break and can return a value directly.
java int month = 7;
// Switch used as an expression that returns a value String season = switch (month) { case 12, 1, 2 -> "Winter"; case 3, 4, 5 -> "Spring"; case 6, 7, 8 -> "Summer"; case 9, 10, 11 -> "Autumn"; default -> { // For multi-statement cases, use 'yield' System.out.println("Invalid month input."); yield "Unknown"; } };
System.out.println(season); // Output: Summer
Best Practice: Always use the modern switch expression syntax (->) if your JDK version supports it, as it is cleaner and less error-prone.