Back to questions
JuniorTheoryCommon
What does the program print?
public class Main {
public static void main(String[] args) {
int d = 2;
switch (d) {
case 1: System.out.print("a");
case 2: System.out.print("b");
case 3: System.out.print("c");
break;
default: System.out.print("d");
}
}
}bc
- Expecting
b: acasewith a colon does not end on its own; withoutbreakexecution falls intocase 3without checking its value. - Expecting
abcorbcd:switchstarts at the matchingcase, not at the top, and thebreakaftercends it beforedefault.
- How would you make
d = 2print onlyb? - When is falling through to the next case useful on purpose?