Java OCA OCP Practice Question 858

Question

What is the output of the following code snippet?

3: boolean v = true; 
4: int result = 15, i = 10; 
5: do { 
6:   i--; 
7:   if(i==8) v = false; 
8:   result -= 2; 
9: } while(v); 
10: System.out.println(result); 
  • A. 7
  • B. 9
  • C. 10
  • D. 11
  • E. 15
  • F. The code will not compile because of line 8.


D.

Note

The code compiles without issue, so option F is incorrect.

After the first execution of the loop, i is decremented to 9 and result to 13.

Since i is not 8, v is false, and the loop continues.

On the next iteration, i is decremented to 8 and result to 11.

On the second execution, i does equal 8, so v is set to false.

At the conclusion of the loop, the loop terminates since v is no longer true.

The value of result is 11, and the correct answer is option D.




PreviousNext

Related