Java switch with constant vs non-constant case labels and fall-through: what happens here?\n\npublic class Switch2 {\n final static short x = 2;\n public static int y = 0; // not constant expression\n public static void main(String [] args) {\n for (int z = 0; z < 3; z++) {\n switch (z) {\n case y: System.out.print("0 "); // Line 11\n case x - 1: System.out.print("1 "); // Line 12\n case x: System.out.print("2 "); // Line 13\n }\n }\n }\n}

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.
  • 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.

More Questions from Flow Control

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion