5.11. Answers to sample exam questions


What’s the output of the following code?

class Loop2 {
    public static void main(String[] args) {
        int i = 10;
            while (i < 15)
                i = i + 20;
        while (i < 2);
  1. 10
  2. 30
  3. 31
  4. 32

Answer: b

Explanation: The condition specified in the do-while loop evaluates to false (because 10<2 evaluates to false). But the control enters the do-while loop because the do-while loop executes at least once—its condition is checked at the end of the loop. The while loop evaluates to true for the first iteration and adds 20 to i, making it 30. The while loop doesn’t execute for the second time. Hence, the value of the variable i at the end of the execution of the previous code is 30.


Get OCA Java SE 8 Programmer I Certification Guide now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.