Thursday, October 18, 2007

Does Java pass by reference or pass by value?

Link

Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.
-------------------------------------------------------------------------------------------------
int x = 5;
int y = 7;

int tmp = x;
x = y;
y = tmp,

If all your variables are local to one method, it doesn't matter whether
they are primitives or references, you can use their values any way you
like.
The problem, which you don't seem to have grasped, comes when these
variables are passed onto other methods.

In C you can do this:

void swap(int *x, int *y) {
int tmp = *x;
*x = *y;
*y = tmp;
}

In Java, you can't. Not with primitive types, anyway. But if you have
some sort of wrapper object, you can do this:

void swap(IntWrapper x, IntWrapper y) {
int tmp = x.getValue();
x.setValue(y.getValue());
y.setValue(tmp);
}

You can't do this with java.lang.Integer as it doesn't have methods to
change its value, but you can write your own wrapper class.

int wrapper(sth old)