switch, break & continue
switch replaces multiple if-else checks when you're comparing one variable against several fixed values — a break after each case is essential, otherwise the next case runs too (fall-through).
break stops a loop immediately. continue skips the current iteration and moves to the next one.
switch (day) {
case 1: System.out.println("Mon"); break;
case 2: System.out.println("Tue"); break;
default: System.out.println("Other");
}- switch = a vending machine for one value
- break = stop the loop/switch immediately
- continue = skip this round
The old switch requires a break to avoid fall-through — if you forget the break, control "falls" into the next case too, even if it doesn't match. This has been a very common source of bugs in older Java code.
Java 14+ brought a new "arrow syntax" (case X -> ...) that breaks automatically (no fall-through — the Java designers listened to developer complaints!), and the yield keyword lets a switch expression directly return a value — making code shorter and safer.
| Traditional switch | Modern switch (14+) | |
|---|---|---|
| Fall-through | Yes (break required) | No (automatic) |
| Can return a value? | No (it's a statement) | Yes (it's an expression, via yield) |
| Multiple values in one case | case 1: case 2: | case 1, 2 -> |
// Modern style (Java 14+)
String dayType = switch (day) {
case 1, 7 -> "Weekend";
case 2, 3, 4, 5, 6 -> "Weekday";
default -> "Invalid";
};Since Java 7+, switch also works on String (earlier it only worked on int/char/byte/short/enum) — internally this is implemented using hashCode(). switch stays very clean with an enum, since all possible cases are already fixed, and your IDE can even warn you if a case is missing.
When you have nested loops and need to break/continue straight out of the outer loop (not just the inner one), you use a "label" — give the outer loop a name (like outer:), and write break outer;. Without a label, break only breaks the nearest (innermost) loop.
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) continue outer; // seedha outer loop ki agli iteration
System.out.println(i + "," + j);
}
}