Java switch with constant vs non-constant case labels and fall-through: what happens here? public class Switch2 { final static short x = 2; public static int y = 0; // not constant expression public static void main(String [] args) { for (int z = 0; z < 3; z++) { switch (z) { case y: System.out.print("0 "); // Line 11 case x - 1: System.out.print("1 "); // Line 12 case x: System.out.print("2 "); // Line 13 } } } }
-
A0 1 2
-
B0 1 2 1 2 2
-
CCompilation fails at line 11.
-
DCompilation fails at line 12.
-
ENo output; program runs silently
Answer
Correct Answer: Compilation fails at line 11.
Explanation
Introduction / Context:
This question tests the requirement that case labels in a switch must be constant expressions known at compile time, and also hints at fall-through behavior (though compilation never gets that far here).
Given Data / Assumptions:
xisfinal static short x = 2→ a compile-time constant.yispublic static int y = 0→ notfinal, thus not a constant expression.- Switch variable is the loop variable
z.
Concept / Approach: Java requires each case label to be a constant expression. case y: uses a non-final variable; the compiler cannot fold it into a constant, so it rejects the code at that line before execution begins.
Step-by-Step Solution: Check label at Line 11: case y: ← invalid because y is not a constant expression. Compiler raises an error referencing Line 11 (or similar wording). Program does not compile; no runtime behavior occurs.
Verification / Alternative check: Change y to final static int y = 0; and the code will compile. Then, with no breaks, output would fall through for each matching case.
Why Other Options Are Wrong: Any output assumes successful compilation. Failing at Line 12 would require an issue with x-1, which is valid since x is final and known at compile time.
Common Pitfalls: Forgetting the final requirement; confusing runtime variable values with compile-time constants; ignoring fall-through only after a successful compile.
Final Answer: Compilation fails at line 11.