OCA Java SE 8 Mock Exam Review - OCA Mock Question 34








Question

What is the output of the following code?

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

public class Main {
  public static void main(String args[]) {
    Person p = new Person();
    p.name = "Main";

    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 
       anotherMethod 
       someMethod 
       someMethod 

    b  anotherMethod 
       Main 
       someMethod 
       someMethod 

    c  anotherMethod 
       Main 
       someMethod 
       Main 

    d  Compilation error. 





Answer



B

Note

The class Main defines two methods, someMethod and anotherMethod.

The main method is the entry point.

someMethod modifies the value of the object parameter passed to it. The changes are visible within this method and the calling method (method main).

anotherMethod reassigns the reference variable passed to it. Changes to any of the values of this object are limited to this method.

public class Main {
  public static void main(String args[]) {
    Person p = new Person();
    p.name = "Main";
/* ww  w. ja  va2  s  .c o  m*/
    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);
  }
}

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

The code above generates the following result.