nerdexam
Oracle

1Z0-803 · Question #164

Given: public class Test { public static void main(String[] args) { int i = 1; do { if ( i % 2 == 0) continue; if (i == 5) break; System.out.print(i + "\t"); i++; } while (true); } } What is the resul

The correct answer is E. Prints 1 once and the loop executes infinite times.. The loop prints '1' during its first iteration, then i becomes 2. In subsequent iterations, since i is always 2 (even), the continue statement is repeatedly hit, preventing i from incrementing further and causing an infinite loop.

Using Loop Constructs

Question

Given:

public class Test { public static void main(String[] args) { int i = 1; do { if ( i % 2 == 0) continue; if (i == 5) break; System.out.print(i + "\t"); i++; } while (true); } } What is the result?

Options

  • A1 3
  • B2 4
  • CThe program prints nothing.
  • DPrints 1 infinite times.
  • EPrints 1 once and the loop executes infinite times.

How the community answered

(44 responses)
  • A
    5% (2)
  • B
    14% (6)
  • C
    2% (1)
  • D
    2% (1)
  • E
    77% (34)

Why each option

The loop prints '1' during its first iteration, then `i` becomes `2`. In subsequent iterations, since `i` is always `2` (even), the `continue` statement is repeatedly hit, preventing `i` from incrementing further and causing an infinite loop.

A1 3

This is incorrect because the loop goes infinite after printing '1', it does not print '3'.

B2 4

This is incorrect because `i` is never printed when it's an even number due to the `continue` statement.

CThe program prints nothing.

This is incorrect because `1` is printed in the first iteration.

DPrints 1 infinite times.

This is incorrect because `1` is printed only once, not infinite times, before `i` becomes `2` and the loop enters an infinite `continue` cycle.

EPrints 1 once and the loop executes infinite times.Correct

In the first iteration, `i` is `1` (odd), so '1' is printed and `i` increments to `2`. In all subsequent iterations, `i` is `2` (even), which triggers the `if (i % 2 == 0) continue;` statement. The `continue` statement immediately skips the rest of the loop body, including `i++`, and jumps to the `while` condition. This causes `i` to remain `2` indefinitely, resulting in an infinite loop that prints '1' only once.

Concept tested: Java do-while loop control flow with continue and break

Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

Topics

#do-while loop#continue statement#infinite loop#loop tracing

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice