Java OCA OCP Practice Question 2393

Question

Given the following definition of class Person,

class Person { 
    public String name; 
    public int height; 
} 

what is the output of the following code?

class Main { /* w  w w .j  a  va2 s. c o  m*/
    public static void main(String args[]) { 
        Person p = new Person(); 
        p.name = "EJava"; 
        anotherMethod(p); 
        System.out.println(p.name); 
        someMethod(p); 
        System.out.println(p.name); 
    } 

    static void someMethod(Person p) { 
        p.name = "someMethod"; 
        System.out.println(p.name); 
    } 
    static void anotherMethod(Person p) { 
        p = new Person(); 
        p.name = "anotherMethod"; 
        System.out.println(p.name); 
    } 
} 
a  anotherMethod //w w  w  . ja v  a2 s. co m
   anotherMethod 
   someMethod 
   someMethod 

b  anotherMethod  
   EJava 
   someMethod 
   someMethod 

c  anotherMethod  
   EJava 
   someMethod 
   EJava 

d  Compilation error 


b

Note

The class Main defines two methods, someMethod() and anotherMethod().

The method someMethod() modifies the value of the object parameter passed to it.

Hence, the changes are visible within this method and in the calling method (method main).

But the method anotherMethod() reassigns the reference variable passed to it.

Changes to any of the values of this object are limited to this method.

They aren't reflected in the calling method (the main method).




PreviousNext

Related