Switch Statements
Overview
Sometimes you have a variable that can be one of many specific values (like the days of the week, or options in a menu). Writing a massive chain of `if -> else if -> else if -> else if` gets very ugly and hard to read.
A Switch Statement is a much cleaner way to handle this. It takes a single variable and 'switches' the execution path based on matching 'cases'.
1. The Anatomy of a Switch
You provide a variable to the switch. Inside, you define multiple `case` blocks. If the variable matches a case, that block runs.
2. The 'break' Keyword
In traditional switch statements, you MUST put a `break;` at the end of each case. If you forget, the code will 'fall through' and execute the next cases even if they don't match!
3. Modern Switch (Java 14+)
Modern Java introduced a beautiful new syntax using an arrow `->`. It removes the need for `break` entirely, preventing the fall-through bug.
Syntax
Notice how every case ends with a break. The 'default' acts like an 'else' block.
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day!");
}Much cleaner, no 'break' needed. Available in modern Java versions.
String status = "SHIPPED";
switch (status) {
case "PENDING" -> System.out.println("Order is being prepared.");
case "SHIPPED" -> System.out.println("Order is on the way!");
case "DELIVERED" -> System.out.println("Package arrived.");
default -> System.out.println("Status unknown.");
}Common Pitfalls
- Forgetting the `break` keyword in a traditional switch. This causes everything below the matched case to execute, creating nasty bugs.
- Switch statements cannot be used with complex logic (like `case > 10`). They only work for exact value matches (like `case 10`).
Interview Tips
- Interviewers love asking about the 'fall-through' behavior in traditional switch statements. Make sure you understand why `break` is necessary.
Real-World Example
Switch statements are perfect for handling user selections in a menu, or processing states in a machine.
public class GameMenu {
public static void handleInput(int userChoice) {
switch (userChoice) {
case 1 -> System.out.println("Starting New Game...");
case 2 -> System.out.println("Loading Saved Game...");
case 3 -> System.out.println("Opening Settings...");
case 4 -> System.out.println("Quitting to Desktop...");
default -> System.out.println("Please press a valid button.");
}
}
}