nerdexam
Oracle

1Z0-809 · Question #139

Given the code fragment: ``java public static void main(String[] args) { int j = 0; int ii = 7; for (int i = 0; i < ii; i = i + 2) { j = j + i; } System.out.print(ii + " " + j); } `` What is the…

The correct answer is A. 0 2 4. Tracing through this code reveals that the marked answer A is actually incorrect - this appears to be a flawed exam question. What the code actually does: | i | Condition (i < 7) | j = j + i | |---|---|---| | 0 | true | 0 + 0 = 0 | | 2 | true | 0 + 2 = 2 | | 4 | true | 2 + 4 =…

Question

Given the code fragment:
public static void main(String[] args) {
 int j = 0;
 int ii = 7;
 for (int i = 0; i < ii; i = i + 2) {
 j = j + i;
 }
 System.out.print(ii + " " + j);
}
What is the result?

Options

  • A0 2 4
  • B0 2 4 6
  • C2 4
  • DCompilation fails.

How the community answered

(21 responses)
  • A
    71% (15)
  • B
    10% (2)
  • C
    14% (3)
  • D
    5% (1)

Explanation

Tracing through this code reveals that the marked answer A is actually incorrect - this appears to be a flawed exam question.

What the code actually does:

iCondition (i < 7)j = j + i
0true0 + 0 = 0
2true0 + 2 = 2
4true2 + 4 = 6
6true6 + 6 = 12
8false - loop ends-

After the loop: ii = 7, j = 12.

System.out.print(ii + " " + j) outputs 7 12.

Why none of the choices are correct:

  • A (0 2 4) - incorrect; that would require printing i inside the loop with ii < 6, neither of which is true here
  • B (0 2 4 6) - those are the values i takes, but they aren't what gets printed
  • C (2 4) - no path produces this
  • D (Compilation fails) - the code is syntactically valid Java

The actual answer is 7 12, which is not among the choices. This is a defective question - either the print statement or the answer choices contain a typo. When you encounter a question like this on an exam, trust your loop trace over the listed choices. The key skill being tested is tracking i and j separately through each iteration.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice