Java OCA OCP Practice Question 1772

Question

What will be the result of attempting to compile and run the following code?

public class Main {
 public static void main(String[] args) {
   boolean b = false;
   int i = 1;/*from w  w  w .ja v a 2  s .  c  om*/
   do {
     i++;
     b = ! b;
   } while (b);
   System.out.println(i);
 }
}

Select the one correct answer.

  • (a) The code will fail to compile because b is an invalid conditional expression for the do-while statement.
  • (b) The code will fail to compile because the assignment b = ! b is not allowed.
  • (c) The code will compile without error and will print 1, when run.
  • (d) The code will compile without error and will print 2, when run.
  • (e) The code will compile without error and will print 3, when run.


(e)

Note

The loop body is executed twice and the program will print 3.

The first time the loop is executed, the variable i changes from 1 to 2 and the variable b changes from false to true.

Then the loop condition is evaluated.

Since b is true, the loop body is executed again.

This time the variable i changes from 2 to 3 and the variable b changes from true to false.

The loop condition is now evaluated again.

Since b is now false, the loop terminates and the current value of i is printed.




PreviousNext

Related