Java OCA OCP Practice Question 3012

Question

Given:

public class Main {
   Main s;/*from  www  .j  a  va2s.co m*/

   public static void main(String[] args) {
      Main s1 = new Main();
      s1.s = new Main();
      go(s1.s);
      Main s2 = go(s1);
      if (s2.s.equals(s1))
         System.out.print("1 ");
      if (s2.equals(s1))
         System.out.print("2 ");
      if (s1.s.equals(s1))
         System.out.print("3 ");
      if (s2.s.equals(s2))
         System.out.print("4 ");
   }

   static Main go(Main s) {
      Main gs = new Main();
      gs.s = s;
      return gs;
   }
}

What is the result?

  • A. 1
  • B. 1 2
  • C. 1 2 4
  • D. Compilation fails.
  • E. "1 ", followed by an exception.
  • F. "1 2 ", followed by an exception.


A is correct.

Note

Main doesn't override equals(), so equals() returns true only when both references are referring to the same object.

Similar to garbage collection questions, the best way to approach this question is to make a diagram of the reference variables, objects, connections between them, and when connections or references are lost.




PreviousNext

Related