Why Java sends the parameters by value

Posted by on mai 02, 2007
Fără categorie

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.

1 Comment to Why Java sends the parameters by value

Dă-i un răspuns lui CoderTricks » Blog Archive » Call by sharing Anulează răspunsul

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest site folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.