Java OCA OCP Practice Question 730

Question

What will the following code print?

public class Main{ 
        int x = 5; 
        int getX (){ return x;  } 

        public static void main (String args []) throws Exception{ 
            Main tc = new Main (); 
            tc.looper (); // w ww.  ja v a2s . c  o m
            System.out.println (tc.x); 
         } 
         
        public void looper (){ 
            int x = 0; 
            while (  (x = getX ())  != 0 ){ 
                for (int m = 10; m>=0; m--){ 
                    x = m; 
                 } 
             } 
             
        }      
} 

Select 1 option

  • A. It will not compile.
  • B. It will throw an exception at runtime.
  • C. It will print 0.
  • D. It will print 5.
  • E. None of these.


Correct Option is  : E

Note

looper() declares an automatic variable x, which shadows the instance variable x.

So when x = m; is executed, it is the local variable x that is changed not the instance field x.

So getX() never returns 0.

If you remove int x = 0; from looper(), it will print 0 and end.




PreviousNext

Related