Java OCA OCP Practice Question 1834

Question

What will the following code print when compiled and run:

public class Main  {

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

Select 1 option.

  • A. 1
  • 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  : F

Note

In Java, a while or do/while construct takes an expression that returns a boolean.

The expression --i is an integer, which is invalid and so the compilation fails.

You could change it to: while ( --i>0 ){ ... }.

In this case, --i<0 is a boolean expression and is valid.




PreviousNext

Related