Some students learn that parameter passing in Java is done by reference. In fact, Java only sends parameters by value, and those parameters are either primitive types or references, never actual objects. If you define a variable in Java which is not in a primitive type, you actually define a reference. So, when you write
Object a = new Object();
what happens is that a is a reference and its value is actually the address of the heap area containing the object.
Now, let’s say you have something like:
void aFunction(Object b)
{
b = "blah";
}
....................................................
Object a = new Object();//we define a as a new object
aFunction(a);//we call the function
System.out.println(a.toString());//NOT "blah"
What happens here is that the function aFunction receives a as an actual parameter, it copies the parameter’s value (which is an address, NOT the object you created with new) and then modifies the copy. Of course, a still has the unchanged value when aFunction returns.
Some people argue that this is passing by reference, because the object that a points to can be changed. This is true, however, as we’ve seen, the object is not passed as a parameter.
You can find a formal analysis of this subject here.
[…] by sharing Java, Python, Functional Programming June 15th, 2007 Powered by Gregarious (42)In a previous article, I was saying trying to convince you that Java passes its parameters by value. Although this is the […]