Java OCA OCP Practice Question 1503

Question

What will the following program print when run?

public class Main  { 

    private int myValue = 0; 
     /* ww  w. j a  v a2 s . c o  m*/
    public void showOne (int myValue){ 
        myValue = myValue; 
        System.out.println (this.myValue); 
     } 
     
    public void showTwo (int myValue){ 
        this.myValue = myValue; 
        System.out.println (this.myValue); 
     }     
    public static void main (String [] args)  { 
        Main ct = new Main (); 
        ct.showOne (100); 
        ct.showTwo (200); 
     } 
} 

Select 1 option

  • A. 0 followed by 100.
  • B. 100 followed by 100.
  • C. 0 followed by 200.
  • D. 100 followed by 200.


Correct Option is  : C

Note

Within an instance method, you can access the current object of the same class using 'this'.

When you access this.myValue, you are accessing the instance member myValue of the Main instance.

Within the showOne() method, there are two variables accessible with the same name myValue.

If you declare a local variable or a method parameter with the same name as the instance field name, the local variable "shadows" the member field.




PreviousNext

Related