Switch Statement
1. When to Use (beginner)
Switch = clean multi-choice for one variable against constants (day number → name). Cleaner than 7 if-else! Works on int, char, String, enum (not double/boolean!).
2. Classic Code (with break!)
int day = 3;
switch (day) {
case 1: System.out.println("Mon"); break; // break STOPS fall-through!
case 2: System.out.println("Tue"); break;
case 3: System.out.println("Wed"); break;
default: System.out.println("Invalid"); // catch-all (like else)
}
// Output: Wed
String switch (Java 7+):
String s = "red";
switch (s) {
case "red": System.out.println("stop"); break;
case "green": System.out.println("go"); break;
default: System.out.println("?");
}
3. Fall-Through Trap (the famous exam bug!)
int x = 1;
switch (x) {
case 1: System.out.print("one "); // NO break → falls!
case 2: System.out.print("two "); // NO break → falls!
default: System.out.print("other");
}
// Output: one two other (all three! — missing breaks!)
Grouping trick (intentional fall-through):
switch (ch) {
case 'a': case 'e': case 'i': case 'o': case 'u':
System.out.println("vowel"); break;
default: System.out.println("consonant");
}
4. Traps
- No
break→ falls through (most-asked output bug!). switchondouble/float/boolean/long= ERROR.- Modern arrow form (Java 14+):
case 1 -> System.out.println("Mon");(no fall-through!).
5. Exam Points
- Day-name program + fall-through output — 5-7 marks, very frequent.
- Allowed types +
breakrole — 3 marks, frequent.