1Z0-803 · Question #218
Given the code fragment: What is the result?
The correct answer is A. 10 8 6 4 2 0. The question asks to predict the output of a while loop that iteratively prints an integer and decrements it by two until it is less than zero.
Question
Given the code fragment:
What is the result?
Exhibit
Options
- A10 8 6 4 2 0
- B10 8 6 4 2
- CAnArithmeticException is thrown at runtime
- DThe program goes into an infinite loop outputting: 10 8 6 4 2 0. . .
- ECompilation fails
How the community answered
(24 responses)- A79% (19)
- C4% (1)
- D4% (1)
- E13% (3)
Why each option
The question asks to predict the output of a `while` loop that iteratively prints an integer and decrements it by two until it is less than zero.
The `while` loop initializes `x` to 10 and continues as long as `x` is greater than or equal to 0 (implicitly `x >= 0` based on the correct answer). Inside the loop, `x` is printed, and then decremented by 2. This process continues until `x` becomes -2, resulting in the output "10 8 6 4 2 0 ".
This output would occur if the loop condition was `x > 0`, causing the loop to terminate before `x` reaches 0 and is printed.
There are no operations in the code, such as division by zero, that would cause an `ArithmeticException` to be thrown.
The value of `x` is consistently decremented, ensuring that the loop condition eventually becomes false and the loop terminates, preventing an infinite loop.
The code fragment uses standard Java syntax and primitive type operations correctly, so it would compile successfully without errors.
Concept tested: While loop control flow and integer arithmetic
Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Topics
Community Discussion
No community discussion yet for this question.
