5.11. Answers to sample exam questions

Q5-1.

What’s the output of the following code?

class Loop2 {
    public static void main(String[] args) {
        int i = 10;
        do
            while (i < 15)
                i = i + 20;
        while (i < 2);
        System.out.println(i);
    }
}
  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.

Q5-2.

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.