Difficulty: Easy
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:
x
is final static short x = 2
→ a compile-time constant.y
is public static int y = 0
→ not final
, thus not a constant expression.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.
Discussion & Comments