Multiple choice technology programming languages

What is the result when you compile and run the following code? public class Test { public void method() { for(int i = 0; i < 3; i++) { System.out.print(i); } System.out.print(i); } }

  1. 0122

  2. 0123

  3. Compilation error

  4. None of these

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

The variable i is declared within the for-loop initialization (int i = 0), so its scope is limited to the loop block. The statement System.out.print(i) outside the loop cannot access i because it's out of scope, causing a compilation error. Option B would be correct if i were declared before the loop.

AI explanation

Compilation error is correct. The variable i is declared in the for-loop's initialization (for(int i = 0; ...)), which means its scope is limited to the for statement itself (including its body). Once the loop ends, i goes out of scope. The final System.out.print(i); statement, placed after the closing brace of the for-loop but still inside method(), refers to an i that no longer exists in that scope, so the compiler reports 'cannot find symbol' — a compilation error. This is a classic Java scoping question: to print i after the loop, it would need to be declared outside the for statement.