Identify the correct outcome of this Java switch with comma-separated labels (which are invalid in Java). What happens at compile time? int i = l, j = -1; // Note: the source uses the letter l, not digit 1 switch (i) { case 0, 1: j = 1; // invalid Java syntax (comma in case label) case 2: j = 2; default: j = 0; } System.out.println("j = " + j);
-
Aj = -1
-
Bj = 0
-
Cj = 1
-
DCompilation fails.
-
Ej = 2
Answer
Correct Answer: Compilation fails.
Explanation
Introduction / Context:This question checks knowledge of valid switch syntax and identifier usage in Java. It intentionally includes two separate compile-time problems to see if you can spot either.
Given Data / Assumptions:
- The initializer uses
int i = l;wherelis a lowercase letter, not the digit 1, and is undefined. - The
caseline usescase 0, 1:, which is not legal Java syntax (Java does not allow comma-separated case labels on one line).
Concept / Approach:Java requires each case label to be written individually, for example case 0: on one line, case 1: on another. Also, every variable must be declared before use. Either violation causes compilation to fail.
Step-by-Step Solution:Undefined identifier: l has no declaration ⇒ compile-time error.Invalid syntax: case 0, 1: also triggers a syntax error.Because compilation fails, the program produces no runtime output.
Verification / Alternative check:Fix the code to int i = 1; and use separate labels case 0: and case 1:; then re-run to observe normal behavior.
Why Other Options Are Wrong:All printed results assume successful compilation and execution, which cannot happen given the errors.
Common Pitfalls:Confusing the letter l with the digit 1; thinking comma-separated case labels are valid in Java (they are not).
Final Answer:Compilation fails.