Java OCA OCP Practice Question 1382

Question

What will the following class print when compiled and run?

public class Main {
   int value = 1;
   Main v;/*  w w w.  j a  va 2 s.co  m*/

   public Main(int val) {
      this.value = val;
   }

   public static void main(String[] args) {
      final Main a = new Main(5);
      Main b = new Main(10);
      a.v = b;
      b.v = setIt(a, b);
      System.out.println(a.v.value + " " + b.v.value);
   }

   public static Main setIt(final Main x, final Main y) {
      x.v = y.v;
      return x;
   }

}

Select 1 option

  • A. It will not compile because 'a' is final.
  • B. It will not compile because method setIt() cannot change x.v.
  • C. It will print 5, 10.
  • D. It will print 10, 10.
  • E. It will throw an exception when run.


Correct Option is  : E

Note

For Option A.

'a' is final is true, a will keep pointing to the same object for the entire life of the program.

The object's internal fields, however, can change.

For Option B.

Since x and y are final, the method cannot change what x and y to point to some other object but it can change the objects' internal fields.

For Option E.

When method setIt() executes, x.v = y.v, x.v becomes null because y.v is null so a.v.value throws NullPointerException.




PreviousNext

Related