Java labeled break exiting nested loops — what prints (if anything)? i = 0; j = 5; tp: for (;;) { i++; for (;;) { if (i > --j) { break tp; // exits the outer loop } } System.out.println("i =" + i + ", j = " + j); } Determine the program’s behavior.
-
Ai = 1, j = 0
-
Bi = 1, j = 4
-
Ci = 3, j = 4
-
DCompilation fails.
Answer
Correct Answer: Compilation fails.
Explanation
Introduction / Context:This question examines labeled break behavior and whether the provided snippet, as written, is syntactically complete. A labeled break can exit an outer loop immediately; however, you must also consider code structure and braces.
Given Data / Assumptions:
- Two infinite loops are shown; the inner loop decrements j (pre-decrement) and compares with i.
- A labeled break (break tp) is used to exit the outer loop when the condition is met.
- The snippet, as presented, omits the closing braces required after the println and the outer loop.
Concept / Approach:As-is, the snippet has unbalanced braces and thus will not compile. If we conceptually repair the braces, the labeled break would trigger before the println executes, because the inner loop’s condition i > --j eventually becomes true and exits the outer loop immediately, bypassing the print inside the outer loop. But the MCQ asks about the given code, not a corrected version.
Step-by-Step (if it were complete):
First outer iteration: i=1.Inner loop: j decrements 5→4→3→2→1→0; when j becomes 0, i(=1) > 0 is true; break tp exits outer loop.No println executes (it is after the inner loop in the same iteration).Why Other Options Are Wrong for the given snippet:
- All printed outputs assume successful compilation; the shown code is syntactically incomplete.
Common Pitfalls:Ignoring brace balance in snippets and focusing only on logic. Real Java source must be well-formed to compile.
Final Answer:Compilation fails.