Grouped labels and a missing break — Aptitude Question
Grouped labels and a missing break: What does this Java program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 90 seconds
Question
What does this Java program print?
public class Main {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
case 2:
System.out.print("Early");
break;
case 3:
case 4:
System.out.print("Mid");
case 5:
System.out.print("Late");
break;
default:
System.out.print("Weekend");
}
}
}Options
- Mid
- MidLate
- MidLateWeekend
- EarlyMidLate
Show the answer and the worked solution
Correct answer: B. MidLate
Worked solution
- day = 3 matches case 3, and the code that follows the pair 3 and 4 prints Mid.
- That group has no break, so execution falls through into case 5 and prints Late.
- case 5 ends in break, so default is never reached and the output is MidLate.
Answer: MidLate.
The idea
Empty stacked labels are a deliberate way to give several values the same body; a missing break at the end of a body is usually a bug. Both appear in the same switch here, and only the break tells them apart.
Shortcut. Jump to case 3 and read down to the first break: Mid, then Late (no break in between), then break.
Common trap. "Mid" assumes each group of labels ends at the next case label; without a break, execution falls into case 5 and prints Late.
All Programming Fundamentals questions · placement mock tests