It's not a secret anymore!*
The moose likes Java in General and the fly likes call by value or call by reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Reply locked New topic
Author

call by value or call by reference

madhu gadde
Greenhorn

Joined: May 27, 2005
Posts: 11
Hi all,
which type of passing tecnique java using.
i know string are only call by value.what about other type of objects.
just give me an idea
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

Java passes everything by value.


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Paul is right, but this usually needs a bit more clarification. Should probably be in the FAQ. Or probably is.

Java always makes a copy of the argument and passes the copy. The called method has a local copy of the data. If the method changes the data it changes the copy, so the original value is not changed.

When we pass a primitive like int this make perfect sense. The method gets its own int variable, a copy of the original.

When we pass an object we have to think very precisely. The value that is copied and sent along is a reference or pointer to the object. The method gets its own copy of the pointer, but it doesn't get its own copy of the object. If the method changes its copy of the pointer to point to a different object the original pointer is not affected. If the method changes some of the attributes of the object, it changes the original object.

Whew! Did that make sense?


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Stan James:
Paul is right, but this usually needs a bit more clarification. Should probably be in the FAQ. Or probably is.


http://faq.javaranch.com/view?CallByReferenceVsCallByValue

Whew! Did that make sense?


So much sense that I used it to replace the present text in the FAQ (which was a little bit confusing, in my opinion).


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Ganesh Gowtham
Ranch Hand

Joined: Mar 30, 2005
Posts: 225

Originally posted by Ilja Preuss:


So much sense that I used it to replace the present text in the FAQ (which was a little bit confusing, in my opinion).



Hi preuss..
So after i read that link ...
I just wrote a snippet could u pls explain ..
i think as of my knowledge it is working as contracdictory ..pls
let me know if what i taught is wrong




why that p[0] is printed in console as Gowtham rather than what we given in console .. it stills over rides ...

Thanks in advance
Gowtham
grgowtham_cse@yahoo.com


Thanks, Ganesh Gowtham
http://ganesh.gowtham.googlepages.com
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
The JVM made an array of the arguments given on the command line. It made a COPY of the pointer to that array and passed it along as the argument. That's textbook "by value" processing.

Given that copy of the pointer your main method can modify the contents of the array. Your method cannot change the original pointer to point to a new array though, because you only have a copy of the pointer.

Does that make sense? We can make some longer examples if you like.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
FYI.
Does Java pass method parameters by reference, by value, both or neither?
http://qa.jtiger.org/GetQAndA.action?qids=37&showAnswers=true

Also on a related note.
What is the difference between an object and an object reference?
http://qa.jtiger.org/GetQAndA.action?qids=75&showAnswers=true
[ July 03, 2005: Message edited by: Tony Morris ]

Tony Morris
Java Q&A (FAQ, Trivia)
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
I prefer simple explanations. Java is always call-by-value. Confusion on this point stems from a simple misunderstanding. When an object is called for the reference value is passed: call-by-value.

Still, that begs the question: what is call-by-reference? Take the fictional Latrino language which supports true call-by-reference:

foo()
{
double x = 1.67
Blob blob = new Blob()
bar( blob, x )

assert blob instanceof Noob // TRUE: Latrino is call-by-reference
assert x > 1.67 // TRUE: Latrino is call-by-reference
}

bar( Blob goop, double mint )
{
goop = new Noob()
mint = 3.14
}
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Gowtham, in this case the thing passed is a pointer to an array, which you have called 'p.' There is only 1 array. no copy of this array is created. What you have now is

1 pointer to an array
1 array

It may be tough for you to understand since arrays can appear to behave differently. Try creating a similar example but not using the main method and not passing an array. try passing an int or Object.
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

Java is pass(or call)-by-value. Always.

A friend of mine gave what I thought is an excellent analogy...

Say you give me a piece of paper that has the address of a house written on it. Now, say I go to the house at that address and rearrange the furniture inside; you'll see the rearranged furniture when you visit the house, since we both held the same address.

Say you give me another piece of paper with the old address again. Now, say I take the paper, erase the address and write a different address on it. You won't see any changes I make to my paper or the new house; you've still got the old address.
Anoop Kavalloor
Greenhorn

Joined: Sep 06, 2004
Posts: 15
Dear all,
just a simple solution. Java uses pass by value for both primitive and Objects. in case of primitive, it is a straight as an arrow. But for Object types,java passes the value of the reference. So what actually the calling method recieves is the copy of the reference of the object. hope it is clear.


I am not completely useless.<br />I can be used as a bad example.<br /> <br />SCJP 1.4
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Anoop Kavalloor:
Dear all,
just a simple solution. Java uses pass by value for both primitive and Objects. in case of primitive, it is a straight as an arrow. But for Object types,java passes the value of the reference. So what actually the calling method recieves is the copy of the reference of the object. hope it is clear.


There is a subtle point here that is a cause for confusion, at least, in my experience (as a university teacher that is). Java does not pass objects, not ever. In fact, objects don't even have names, which makes it difficult to discuss. For example:
Object o = new Object();
There is an object there, but it has no name. There is also a reference, called 'o' - it has a name. We can talk about the object by saying 'the object that o refers to', but otherwise, nothing else is accurate.

Java passes all types (reference and primitive) by value. Objects are not types (despite what your teacher might tell you); they are merely objects.

Does this sound like the Semantic Police? Certainly not according to all the confusion that I see as a result. It's much more than a mere issue of semantics.

See if this helps:
http://qa.jtiger.org/GetQAndA.action?qids=75&showAnswers=true
Juan Rolando Prieur-Reza
Ranch Hand

Joined: Jun 20, 2003
Posts: 236
Paraphrase of madhu gadde:
Hi all,
which type of passing technique does java use?.


The answer to this is simple. If the argument is a primitive type, then it is passed by value. If the argument is a reference to an object, then it is considered pass-by-reference.

Actually, "under the hood," the same mechanism is used. It just happens that if you pass the value of a reference, it has the effect of pass-by-reference. Therefore, authoritative sources call it pass-by-reference. Objects are not copied. Only the reference to them.
See page 133 of Sun Certified Programmer for Java 2 ISBN 0-07-213208-6, or similar source covering Objective 3.03.

This question belongs in the introductory thread.


Juan Rolando Prieur-Reza, M.S., LSSBB, SCEA, SCBCD, SCWCD, SCJP/1.6, IBM OOAD, SCSA
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by john prieur:
Therefore, authoritative sources call it pass-by-reference.


Actually, authoritative sources are always very careful to call it "pass by value" and go through the whole explanation of how references are passed by value. Anybody who says otherwise is not with the program, I'm afraid.


[Jess in Action][AskingGoodQuestions]
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
The authoritative source says quite the contrary.
Specifically, VM Specification 2.10.1
'When the method is invoked, the values of the actual argument expressions initialize newly created parameter variables (�2.5), each of the declared type, before execution of the body of the method.'
Can't get any more 'explicit' or 'authoritative' than that surely?

Any other "authoritative source" is codswallop. Technical books, marketing hype, brochures on the latest buzzword, etc. are not authoritative sources. Particularly since their primary agenda has nothing at all to do with portraying correctness.
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
>> The authoritative source says quite the contrary.

The specification is entirely consistent. The distinction betweeen call by value versus reference is something that confuses a lot of new programmers so it's an easy mistake to make.

James Gosling, in The Java Programming Language, stipulates the following:

"All parameters to Java methods are 'pass by value.'"

No matter how explicit or authoratative, what might be crystal clear to one reader could be easily misinterpreted by a naive or uninformed reader. That is why James Gosling's book is such a welcome addition to any library.

>> Any other "authoritative source" is codswallop.

Even if your interpretation was correct, and it's not, broad sweeping statements like that have little value.

>> Particularly since their primary agenda has nothing at all to do with portraying correctness.

Would it make a difference? You failed to interpret the plain facts of the specification.
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
>> It just happens that if you pass the value of a reference, it has the effect of pass-by-reference.

A good approximation but incorrect. In true pass-by-reference, no values are copied, not even the reference. So if you called foo(bar) and assigned bar a different value inside foo, the caller's bar reference would reference the new value.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Rick, Tony's got it right here -- he's addressing his comments to John, not to me. He agrees with me, and as we all know, I'm always right
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
My interpretation? You mean the direct quote from the VM Specification? It's correct, you can verify it for yourself if you like.

My paraphrasing of the authoritative source is done as some link that I posted earlier where it's made clear that Java passes all types by value.
Roger Chung-Wee
Ranch Hand

Joined: Sep 29, 2002
Posts: 1683
As this is the Advanced forum, I just thought that I'd mention that pass-by-reference is used in certain special cases. For instance, an EJB Server can improve the performance of Remote Method Interface calls within the server by making direct Java method calls using pass-by-reference when the caller and callee are in the same application and in the same JVM. This requires the deployment of modules together in an EAR file.

If pass-by-value were used instead, there would be the cost of copying objects, marshalling and unmarshalling.


SCJP 1.4, SCWCD 1.3, SCBCD 1.3
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

That has nothing to do with the Java language, but rather with RMI. Here you're talking about serializing and copying a Java object vs. making remote procedure calls on it; that's a decision made in high-level libraries and has nothing to do with the functioning of the JVM.
Juan Rolando Prieur-Reza
Ranch Hand

Joined: Jun 20, 2003
Posts: 236
Tony and Ernest,

Thanks for your comments
Originally posted by Ernest Friedman-Hill:
Rick, Tony's got it right here -- he's addressing his comments to John, not to me. He agrees with me, and as we all know, I'm always right


However, you have not actually identified your authoritative citation (URL, page, etc). Instead, you quoted a source that clearly does not mention pass-by-(reference or value). I'm willing to consider that Sun's publications may have made inconsistent assertions. But show us.

Meanwhile, you can argue with Sun Microsystems authoritative publications, which states in one example:
Notice when an object is passed to a method, any changes that occur inside the method also occur to the object outside the method. This is because the reference variables ... both point to the same object. Hence, a change made within the method changes the data in the same object. The object was passed by reference.

See page 133 of Sun Certified Programmer for Java 2 ISBN 0-07-213208-6.
The italics are in the actual book for emphasis. That is the effect regardless of under-the-hood implementation details. Although training material is not as authoritative as specs, the explanations are sometimes clearer and equally reliable.

[ September 10, 2005: Message edited by: john prieur ]
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
John, you are being mislead by ambiguous lanugage in casual discussion. Did you see my reference to James Gosling who spells out what should be obvious? James Gosling wrote the language in case you were not aware of that. What is in the specification is entirely consistent with that, there's nothing in the specification that indicates call-by-reference.

The problem is that you do not know what call-by-reference means and you are not alone. It is something of a moot point because every Java programmer that has the foggiest idea what they are doing knows how object references work in Java. That in inclues you. I am certain you know what is going on mechanically but you are describing it improperly as pass-by-reference.

Java trips up C++ programmers when they first start using Java. C++ does support true c-b-r but the default is c-b-v. In C++ when you pass on object it creates a copy of the object, just like a primitive. It will even perform a deep copy if your class is in a standard form.

Now, as the reference you cited. It's not the best description but it's not inaccurate. A reference is indeed being passed. That is not the definition of call-by-reference.

I don't think you've failed to grasp this; you simply don't know what the definition is. You are making assumptions that are invalid. Propably three quarters of Java programmers make the same mistake.
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

If the argument is a primitive type, then it is passed by value. If the argument is a reference to an object, then it is considered pass-by-reference.
No; passing a reference does not imply pass-by-reference. Pass-by-reference is not available in Java.

Therefore, authoritative sources call it pass-by-reference.

Here's *the* authority:

All parameters to methods are passed "by value." In other words, values of parameter variables in a method are copies of the values the invoker specified as arguments. If you pass a double to a method, its parameter is a copy of whatever value was being passed as an argument, and the method can change its parameter's value without affecting values in the code that invoked the method. For example:

The following output illustrates that the value of arg inside halveIt is divided by two without affecting the value of the variable one in main:You should note that when the parameter is an object reference, the object reference -- not the object itself -- is what is passed "by value." Thus, you can change which object a parameter refers to inside the method without affecting the reference that was passed. But if you change any fields of the object or invoke methods that change the object's state, the object is changed for every part of the program that holds a reference to it. Here is an example to show the distinction:

This program produces the following output: Notice that the contents of the object have been modified with a name change, while the variable Sirius still refers to the Body object even though the method commonName changed the value of its bodyRef parameter variable to null. This requires some explanation.

The following diagram shows the state of the variables just after main invokes commonName:

At this point, the two variables sirius (in main) and bodyRef (in commonName) both refer to the same underlying object. When commonName changes the field bodyRef.name, the name is changed in the underlying object that the two variables share.

When commonName changes the value of bodyRef to null, only the value of the bodyRef variable is changed; the value of sirius remains unchanged vecause the parameter bodyRef is a pass-by-value copy of sirius. Inside the method commonName, all you are changing is the value in the parameter variable bodyRef, just as all you changed in halveIt was the value in the parameter variable arg. If changing bodyRef affected the value of sirius in main, the "after" line would say "null". However, the variable bodyRef in commonName and the variable sirius in main both refer to the same underlying object, so the change made inside commonName is visible through the reference sirius.

Some people will say incorrectly that objects are passed "by reference." In programming language design, the term pass by reference properly means that when an argument is passed to a function, the invoked function gets a reference to the original value, not a copy of its value. If the function modifies its parameter, the value in the calling code will be changed because the argument and parameter use the same slot in memory. If the Java programming language actually had pass-by-reference parameters, there would be a way to declare halveIt so that the preceding code would modify the value of one, or so that commonName could change the variable sirius to null. This is not possible. The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mod -- pass by value -- and that helps keep things simple.


Reference:
Arnold, K., Gosling J., Holmes D. (2000). The Java� Programming Language Third Edition. Boston: Addison-Wesley.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Thanks, Steve. Can't do much better than JG spelling it out for us.

John, I guess besides arguing about what "pass by reference" means, we're arguing about what "authoritative" means. I would say that study guides for an exam, regardless of who publishes them, are not authoritative. In fact, the content of the exam itself isn't an authoritative source for information about Java. SCJP/D/A study guides are not designed to teach you the Java language. They are designed to teach you to pass the exam, which is a horse of a different color. There's nothing wrong with that, but we do actually have separate forums for discussing those individual parallel universes.

Meanwhile, here in the Java in General forums, we look to the formal specifications (the JLS, the JVMS, J2EE spec, etc) and we have the JPL book, written by the father of Java, which I'd consider to be the Java correlate of the old C++ ARM. Anything else is derivative, not authoritative.
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
Quintessential Example

OK, here's a concrete written in Latrino (my favorite fictional language). A hash mark indicates a reference in Latrino.




Point of interest: My Latrino language is a combination of Latin and Neutrino for no other reason that it sounds cool. Others have observed that is has an excremental quality to it, whatever that means.
[ September 10, 2005: Message edited by: Rick O'Shay ]
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
YALE

(Yet Another Latrino� Example)


[ September 10, 2005: Message edited by: Rick O'Shay ]
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by john prieur:
Tony and Ernest,

Thanks for your comments

See page 133 of Sun Certified Programmer for Java 2 ISBN 0-07-213208-6.
The italics are in the actual book for emphasis. That is the effect regardless of under-the-hood implementation details. Although training material is not as authoritative as specs, the explanations are sometimes clearer and equally reliable.


[ September 10, 2005: Message edited by: john prieur ]


VM Specification 2.10.1
When the method is invoked, the values of the actual argument expressions initialize newly created parameter variables (�2.5), each of the declared type, before execution of the body of the method.

Is it not clear that this is mandating pass by value semantics? What about if I emphasise the "newly create parameter variables" part?

Your example from some arbitrary technical book is a perfect example of why not to use technical books as anything more than they really are - a way for the author(s) to feed his/her children while at least appearing to portray some level of truth as a secondary agenda. Certainly not an authoritative source.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

OK, everybody. That'll do.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: call by value or call by reference