🔀
Basics

switch, break & continue

More Control Flow
💡 switch is like a vending machine — press a number, get exactly that item, instead of checking if-else one by one. break exits a loop; continue skips to the next round.

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 is like a vending machine — press a number, get exactly that item, instead of checking if-else one by one. break exits a loop; continue skips to the next round.
1 / 5
On this page (3 subtopics)

Purana switch fall-through ke saath break maangta hai — agar break bhool gaye, control agle case mein bhi "gir" (fall-through) jaata hai, chahe wo match na kare. Ye ek bahut common bug source raha hai purane Java code mein.

Java 14+ mein naya "arrow syntax" (case X -> ...) aaya jo automatically break kar deta hai (fall-through nahi hota — Java designers ne suna developers ki shikayatein!), aur yield keyword se switch expression se seedha value bhi return kar sakte ho — code chhota aur safer ho jaata hai.

Traditional switchModern switch (14+)
Fall-throughHaan (break zaroori)Nahi (automatic)
Value return kar sakta hai?Nahi (statement hai)Haan (expression hai, yield se)
Multiple values ek case meincase 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";
};

Java 7+ se switch String par bhi kaam karta hai (pehle sirf int/char/byte/short/enum par chalta tha) — internally ye hashCode() use karke implement hota hai. Enum ke saath switch bahut clean rehta hai kyunki saare possible cases pehle se fixed hote hain, aur IDE tumhe warn kar sakta hai agar koi case miss ho gaya.

⚠️Common Mistake: switch(str) mein agar str null hai, NullPointerException aayegi (immediately, switch statement mein hi) — pehle null-check karo agar possibility ho.

Jab nested loops ho aur tumhe seedha outer loop se break/continue karna ho (sirf inner se nahi), tab "label" use karte ho — outer loop ke pehle ek naam de do (jaise outer:), aur break outer; likho. Bina label ke, break sirf sabse nazdeeki (innermost) loop ko todta hai.

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);
  }
}