In Java, what is the exact output and why? Consider scope of the for-loop variable and the print after the loop. for (int i = 0; i < 4; i += 2) { System.out.print(i + " "); } System.out.println(i); // Line 5

Difficulty: Easy

Correct Answer: Compilation fails.

Explanation:

Introduction / Context: This question checks your understanding of Java variable scope for loop-initialized variables versus their visibility outside the loop. Many beginners assume that a loop variable declared inside the for header remains usable after the loop ends, which is not correct in Java.

Given Data / Assumptions:

  • The loop header declares int i locally to the for statement.
  • System.out.print(i + " ") occurs inside the loop body.
  • System.out.println(i) appears after the loop (Line 5).

Concept / Approach: A variable declared in the initialization section of a for loop has scope limited to the loop construct itself. Outside the loop, that identifier is out of scope. Attempting to reference it leads to a compile-time error: “cannot find symbol” (or similar) for i at the println after the loop.

Step-by-Step Solution: Declare: for (int i = 0; i < 4; i += 2)i is local to the for. Inside the loop, printing i is legal. It would output “0 2 ” if compiled. After the loop, i is out of scope. System.out.println(i) therefore triggers a compilation error.

Verification / Alternative check: Move int i above the loop (e.g., int i = 0; then use for (i = 0; ...)). Now the code compiles, printing “0 2 ” from the loop and then the final value of i after the loop.

Why Other Options Are Wrong: Outputs such as “0 2 4” or “0 2 4 5” assume successful compilation and visibility of i after the loop, which is false here.

Common Pitfalls: Confusing C/C++ rules with Java; assuming loop-local variables leak into the outer scope; forgetting that the for-header declaration limits scope to the statement.

Final Answer: Compilation fails.

Discussion & Comments

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