Java OCA OCP Practice Question 3

Question

Given the following classes:


class Wrapper {
   public int x;
}

public class Main {
   private static void bump(int n, Wrapper w) {
      n++;/* www.  j a v  a 2s  . com*/
      w.x++;
   }

   public static void main(String[] args) {
      int n = 10;
      Wrapper w = new Wrapper();
      w.x = 10;
      bump(n, w);
      // Now what are n and w.x?
   }
}

When the application runs,

what are the values of n and w.x after the call to bump() in the main() method?

  • A. n is 10, w.x is 10
  • B. n is 11, w.x is 10
  • C. n is 10, w.x is 11
  • D. n is 11, w.x is 11


C.

Note

Primitives are passed by value, so bump() increments a copy of n, not n itself.

Object references are also passed by value, so bump() uses a copy of w, not w itself.

Since that copy points to the same object as the one pointed to by w, changes made in bump() are permanent.




PreviousNext

Related