Java OCA OCP Practice Question 1053

Question

What will the following code print when compiled and run:

public class Main  { 
    public static void main (String [] args){ 
        int k = 2; 
        do{ 
            System.out.println (k); 
        }while (--k>0); 
     } 
} 

Select 1 option

A.  1 //from  ww w.  j a  va 2s  .c o  m

B.  1 
    0 

C.  2 
    1 

D.  2 
    1 
    0 

E. It will keeping printing numbers in an infinite loop. 

F. It will not compile. 


Correct Option is  : C

Note

--k>0 implies, decrement the value of k and then compare with 0.

The loop will only execute twice, printing 2 and 1.

Had it been k-->0, it would imply, first compare k with 0, and then decrement k.

The loop would execute thrice, printing 2, 1, and 0.




PreviousNext

Related