The switch statement selects one of many code blocks to execute based on a value. It is cleaner than long if/else-if chains when comparing a variable against specific values.
public class SwitchBasics {
public static void main(String[] args) {
String browser = "chrome";
switch (browser) {
case "chrome":
System.out.println("Launching ChromeDriver");
break;
case "firefox":
System.out.println("Launching GeckoDriver");
break;
case "safari":
System.out.println("Launching SafariDriver");
break;
case "edge":
System.out.println("Launching EdgeDriver");
break;
default:
System.out.println("Unsupported browser: " + browser);
}
}
}Every case needs a break statement. Without break, execution falls through to the next case — all remaining cases run until a break is found or the switch ends.
Sometimes you want multiple cases to run the same code. Omit the break intentionally.
public class SwitchFallThrough {
public static void main(String[] args) {
String env = "staging";
switch (env) {
case "dev":
case "staging":
case "qa":
System.out.println("Using test database");
break;
case "prod":
System.out.println("Using production database");
break;
}
}
}public class SwitchInt {
public static void main(String[] args) {
int dayOfWeek = 3;
String day;
switch (dayOfWeek) {
case 1: day = "Monday"; break;
case 2: day = "Tuesday"; break;
case 3: day = "Wednesday"; break;
case 4: day = "Thursday"; break;
case 5: day = "Friday"; break;
case 6: day = "Saturday"; break;
case 7: day = "Sunday"; break;
default: day = "Invalid";
}
System.out.println(day); // Wednesday
}
}Switch works with int, char, String, and enum types. It does NOT work with long, float, double, or boolean.
| Use switch when | Use if/else when |
|---|---|
| Comparing ONE variable against specific values | Comparing ranges (x > 10 && x < 50) |
| 3+ exact-match cases | 1-2 conditions |
| String or int equality checks | Complex boolean expressions |
| Each case is independent | Conditions depend on each other |
Q: What happens if you forget break in a switch statement?
A: Without break, execution falls through — Java continues running all subsequent cases until it hits a break or reaches the end of the switch block. This is called fall-through. It can be used intentionally to group cases but is usually a bug. Every case should end with break unless you deliberately want fall-through behavior.
Exercise 1: Write a switch that takes a test priority ("critical", "high", "medium", "low") and prints the retry count (3, 2, 1, 0 respectively).
Exercise 2: Write a simple calculator using switch. Given two numbers and an operator (+, -, *, /), print the result.