Argument passing in Java revisited

They say “It doesn’t matter till it affects you directly”… very right so!

Recently when doing a Swing application I was amazed how object passing seems to throw surprises at times. In short, object changed / reassigned in one class/method does not always change in another class/method. Hence, my assumption that objects are passed by reference in Java needed some clarification.

That’s when I started delving into more details of the mysterious “argument passing” in Java, which I always tried to avoid by just grabbing the basics. Here is what I discovered:

Arguments are ALWAYS passed by value in Java.

What I knew before was that in Java:

– primitive variables are passed by value

– objects are passed by reference

However, this was “pseudo-truth”. As a matter of fact, in Java all object variables are just “pointers” (references) to the memory locations. This fact is hidden by Java that’s why many developers don’t even know about it.

When such a “reference” is passed as an argument it’s copy is created (which points to the same memory location), hence we have an illusion that objects are passed by reference. But here is where problem occurs. Consider the code below:

swapper(Object x, Object y){
	Object temp = y;
	y = x;
	x = temp;
}

One might consider this function helps to swap variables in an easy way. But it DOESN’T!

The reason is because variables x and y are now local to “swapper” method. Hence, reassigning them would mean nothing to the “calling” method.

NOTE: As expected, changing state of x and y objects within a “swapper” method affects x and y objects in “calling” method.

Leave a comment