nerdexam
Oracle

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.

Using Loop Constructs

Question

Given the code fragment:

What is the result?

Exhibit

1Z0-803 question #218 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)
  • A
    79% (19)
  • C
    4% (1)
  • D
    4% (1)
  • E
    13% (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.

A10 8 6 4 2 0Correct

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 ".

B10 8 6 4 2

This output would occur if the loop condition was `x > 0`, causing the loop to terminate before `x` reaches 0 and is printed.

CAnArithmeticException is thrown at runtime

There are no operations in the code, such as division by zero, that would cause an `ArithmeticException` to be thrown.

DThe program goes into an infinite loop outputting: 10 8 6 4 2 0. . .

The value of `x` is consistently decremented, ensuring that the loop condition eventually becomes false and the loop terminates, preventing an infinite loop.

ECompilation fails

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

#for loop#loop iteration#arithmetic operators#runtime errors

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice