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.
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)- A5% (2)
- B14% (6)
- C2% (1)
- D2% (1)
- E77% (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.
This is incorrect because the loop goes infinite after printing '1', it does not print '3'.
This is incorrect because `i` is never printed when it's an even number due to the `continue` statement.
This is incorrect because `1` is printed in the first iteration.
This is incorrect because `1` is printed only once, not infinite times, before `i` becomes `2` and the loop enters an infinite `continue` cycle.
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
Community Discussion
No community discussion yet for this question.