Why Java sends the parameters by value

Posted by Strainu on May 02, 2007

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.

Share and Enjoy:
  • Facebook
  • Twitter
  • Identi.ca
  • LinkedIn
  • Reddit
  • Add to favorites

1 Comment to Why Java sends the parameters by value

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.