0

Consider the code:

static void incr(Integer n)
{
    n++;
}

public static void main(String args[])
{
   Integer n = 66; // Autoboxing

   incr(n);

   System.out.println(n);
}

The above program outputs 66. I expected it to print 67 and here is why. Boxing a value converts the primitive value to an object, right. In case of objects, Java passes the pointer to the object to a called function, that's incr in the above example. incr() increments the value in the memory cell passed to it. So, the change in value must occur in n too. Now please tell me, what am I missing?

  • 3
    http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Nicolas Filotto Jun 15 '16 at 16:15
  • 2
    `incr` does _not_ increment the value in the memory cell passed to it. It changes the reference to point to a new cell with a value one higher than the value in the cell that was passed to it. `Integer` is immutable; you just made `n` point to a new, higher value. – Louis Wasserman Jun 15 '16 at 16:18
  • 1
    `Integer`s are immutable. You can't change their `int` value, for a very good reason. – bcsb1001 Jun 15 '16 at 16:18

0 Answers0