Java labeled continue usage — does this snippet compile and, if so, what prints? int I = 0; label: if (I < 2) { System.out.print("I is " + I); I++; continue label; } Choose the correct outcome.
-
AI is 0
-
BI is 0 I is 1
-
CCompilation fails.
-
DNone of the above
Answer
Correct Answer: Compilation fails.
Explanation
Introduction / Context:This question tests knowledge of labeled statements and the valid contexts for continue in Java. Although labels can prefix many statements, continue has strict usage rules.
Given Data / Assumptions:
- A label named label: is placed before an if block.
- Inside the if block, the code attempts continue label;.
- No loop (for, while, do-while) is present surrounding the label.
Concept / Approach:In Java, continue (with or without a label) can only target a loop statement. A labeled continue must reference the label of an enclosing loop. Placing a label on a non-loop statement (such as an if) does not create a valid target for continue. The compiler enforces this rule, producing an error such as "continue outside of loop" or "undefined label for continue."
Step-by-Step Solution:
Identify the labeled statement: label: if (...){ ... }Check whether a loop encloses the continue: none does.Therefore the continue label; statement is illegal.The code fails to compile; no output is produced.Verification / Alternative check:Replace the if with a for(;;) loop and keep the label; the code compiles and the labeled continue will jump to the loop’s next iteration.
Why Other Options Are Wrong:
- Any printed output options assume successful compilation.
- "None of the above" is unnecessary because the correct reason is a compile error.
Common Pitfalls:Assuming any labeled statement can be the target of continue; only loops qualify (for, while, do-while).
Final Answer:Compilation fails.