Friday, April 4, 2014

Passing reference by value in Java

Having been sticking to C/C++ for a decade, I know relatively clearly about the notion of "passing by value" and "passing by reference/address", and the memory models behind them. Embarrassingly, however, it is just a recent clarification that "passing reference by value", a freak concept in Java, is not only in essence unequivocally different from the preceding two, but really closely related to them. Most important, this nuance in name but connections underneath is what has been confusing me for all times I was intensively programming in Java for the past two years.

Without re-spinning the explanation, I just simply summarize toward the gist about this topic, using the information in courtesy of Dale King, by posting the core question and the thorough answer to it.


Does Java pass objects by reference or by value? 

The answer is NO! (that is, Java neither passes objects by reference nor does that by value!)

The fact is that Java has no facility whatsoever to pass an object to any function, and the reason is that Java has no variables that contain objects.

It is common to confound the concept of an object reference variable with that of an object instance, but all object instances in Java are allocated on the heap and can only be accessed through object references.

So if I have the following assignment:

String g = new String( "Hello" );

 
The variable g does not contain the string "Hello", it contains a reference (or pointer) to an object instance that contains the string "Hello".

Java only has variables that hold primitives or object references. Both are passed by value. Now, it comes naturally that Java does pass (object's) reference by value. if the parameter being passes is an object (rather than a primitive type of value).

No comments:

Post a Comment