For-loop evaluation order with function calls in header: predict the exact character sequence printed.\n\npublic class Delta {\n static boolean foo(char c) {\n System.out.print(c);\n return true;\n }\n public static void main(String[] argv) {\n int i = 0;\n for (foo('A'); foo('B') && (i < 2); foo('C')) {\n i++;\n foo('D');\n }\n }\n}

Difficulty: Medium

Correct Answer: ABDCBDCB

Explanation:


Introduction / Context:
This question examines the order of execution for the three parts of a Java for loop header (initialization; condition; update) and how many times each executes, alongside short-circuit evaluation in the condition part.


Given Data / Assumptions:

  • foo(c) prints the character and returns true.
  • Loop variable i starts at 0 and is incremented in the body.
  • Condition is foo('B') && (i < 2).


Concept / Approach:
The for loop executes in the order: initialization once, then condition before each iteration, then body, then update after each successful iteration. The condition uses short-circuit AND so it stops evaluating i < 2 only if foo('B') returns false (it does not here).


Step-by-Step Solution:
Initialization: foo('A') prints A.1st condition: foo('B') prints B; i < 2 is true ⇒ enter body.Body: i becomes 1; foo('D') prints D.Update: foo('C') prints C.2nd condition: prints B; i < 2 true ⇒ body prints D; update prints C.3rd condition: prints B; now i < 2 is false ⇒ loop ends, update does not run.Concatenated output: ABDCBDCB.


Verification / Alternative check:
Insert separators (e.g., spaces) to visually confirm the phases: Init(A), Cond(B), Body(D), Upd(C) ...


Why Other Options Are Wrong:
They assume a different order or number of iterations, or a compilation/runtime error which is not present.


Common Pitfalls:
Forgetting that the update step is skipped on the final failed condition check; misunderstanding short-circuit semantics.


Final Answer:
ABDCBDCB

Discussion & Comments

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