Java OCA OCP Practice Question 1133

Question

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

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

Select 1 option

  • A. The code will fail to compile, 'while' has an invalid condition expression.
  • B. It will compile but will throw an exception at runtime.
  • C. It will print 3.
  • D. It will go in an infinite loop.
  • E. It will print 1.


Correct Option is  : C

Note

A. is wrong.

It is perfectly valid because b = !b; returns a boolean, which is what is needed for while condition.

The 'do {} while()' loop executes at least once because the condition is checked after the iteration.




PreviousNext

Related