*
The moose likes Java in General and the fly likes Passed By Reference? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Passed By Reference?" Watch "Passed By Reference?" New topic
Author

Passed By Reference?

Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

Can anyone tell me if objects in JAVA are passed by reference or passed by value, AND show me a link to this information if provided by Sun or another reliable source.
Thanks you
------------------
Happy Coding,
Gregg Bolinger
[This message has been edited by Gregg Bolinger (edited October 17, 2001).]


GenRocket - Experts at Building Test Data
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
There have been numerous heated discussions here and elsewhere, and I've seen even normally expert sources spout nonsense over the subject. All these discussions are so much hot air because although they seem to be about technical matters they are actually merely about semantics - never usefully discussed this way.
Java objects, as objects, are passed by reference.
There is an alternative, equally valid viewpoint whereby you regard the contents of a variable of object type T as a pointer to the actual object on the heap. These references are passed by value.
There is no "wrong" or "right" in this. Choose whatever viewpoint suits your way of thinking best, and this will determine whether you think of method calls as "pass by reference" or "pass by value".
For Java primitives there's no ambiguity: they are passed by value.
This is my reliable source. It discusses reference types here, and the method invocation mechanism here.
- Peter

[This message has been edited by Peter den Haan (edited October 19, 2001).]
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

Thanks Peter. It makes more since to me now. But I am still a tad confused. I will do some more research though.
Thanks Again.

------------------
Happy Coding,
Gregg Bolinger
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
Java is just like C, everything is pass-by-value, period.
How you view it does not change the language itself, and it does not change the Programming Languages Theory definition of pass-by-value either.
In addition to all Peter's link above, a lot more discussion and example code here:
pass-by-value, etc.
Quotation from Dr. Gosling:
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. 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 mode -- pass by value -- and that helps keep things simple.

Quotation from The Java Tutorial

Pass by Value
In Java methods, arguments are passed by value.
When invoked, the method receives the value of the variable passed in. When the argument is of primitive type, pass-by-value means that the method cannot change its value. When the argument is of reference type, pass-by-value means that the method cannot change the object reference, but can invoke the object's methods
and modify the accessible variables within the object.
This is often the source of confusion--a rogrammer writes a method that attempts to modify the value of one its arguments and the method doesn't work as expected. Let's look at such method and then investigate how to change it so that it does what the programmer originally intended.

Thanks!
Roseanne

[This message has been edited by Roseanne Zhang (edited October 18, 2001).]
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

OK, so now I have heard both answers. And so appearntly no one REALLY knows what is going on. Because one person tells me that objects created with 'new' get passed by reference, and then another person comes along and tells me 'everything' gets passed by value.
And no one can show me a certified link on java.sun.com that just says it one way or another in plain english.
Oh well.

------------------
Happy Coding,
Gregg Bolinger
Michael Ernest
High Plains Drifter
Sheriff

Joined: Oct 25, 2000
Posts: 7292

Peter is right, there's been a lot of back and forth over what amounts to perspective. But here's why I'm right when I say Java passes by value.
I'm reluctant to say this with Gregg in the room, but an object reference *is*, for the purposes of parameterization, a pointer. It is not the object itself. Object references describe a datum's type and location in JVM "memory." The overhead on the called method is therefore lightweight: all it has to allocate is a stack variable that can receive that descriptor.
What the called method's local variable cannot do is change what or where the calling method's local variable points to. If you know what a method stack is, that should be easy to see; if not, then taking this concept on faith is problematic.
Nonetheless, the stacks of two methods can't be shared, but one can certainly pass [i]a copy of a reference[/] to the other.
Once you're comfortable with that, it's easier to understand primitives. Primitives also describe type and location. In this special case, however, the location is the value. The same rules accordingly apply.
Where this can get truly murky is in distributed computing. Object references describe location with respect to a single JVM, so we run into trouble when we want to pass a reference from JVM Moe to JVM Curly. But to hear more on that, you're going to have to spend some time in the RMI/CORBA forum....
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide


Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
The first quote is from:
From The Java Programming Language, by James Gosling et al. 3rd edition (pg. 56)
The second quote: http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

The link in the tutorial still is not clear. The way it is explained, the primitives get passed by value, which I already knew. But how about this:
class someClass {
String g = new String()
}

class anotherClass {
someClass c = new someClass()
c.g = "Gregg";
}
Now tell me if that is passed by reference or passed by value. It is not a primitive.

------------------
Happy Coding,
Gregg Bolinger
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
There is subtle reason for the other view (pass-by-reference) in Java seems ok. However, if you say it is ok in C will be a huge mistake!
The reason is Java does not allow pointer (Object reference) dereferencing, which makes Java safer, but less flexible than C.
That is why if you view Pass-Object-Reference-By-Value as pass-object-by-reference does not hurt anything in Java. However, if you view pass-object-pointer-by-value-in-C as pass-object-by-reference-in-C(???) will be a huge mistake, and the whole system will not work.
Remember, I'm talking C only here, since C++ allows pass-by-reference.

Thanks!
Roseanne
[This message has been edited by Roseanne Zhang (edited October 18, 2001).]
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
Gregg
You need read a little more to understand your normal confusion:
Here is an example with detailed explanation: http://www.webappcabaret.com/javachina/jc/Cert/PassByValueEx.htm
Happy learning!
Roseanne
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

Thanks RoseAnn. I will do some more reading. Here is what I was under the impression was happening though.
Passing objects by reference means that you are manipulating the original where as pass by value means you are creating a copy of that object to be manipulated.
Maybe that is more C specific, or maybe I just have my definitions wrong.
And just to clarify, I am not trying to create a debate on what language is better. Just trying to learn this so that when it comes time, I know which language I would prefer to implement my design with.
Thanks for everyones help, and I welcome more of it.
------------------
Happy Coding,
Gregg Bolinger
Michael Ernest
High Plains Drifter
Sheriff

Joined: Oct 25, 2000
Posts: 7292

Originally posted by Gregg Bolinger:
[B]But how about this:

Now tell me if that is passed by reference or passed by value. It is not a primitive.
[/B]

The answer is neither; there's no method call, no parameterization. The "feature" that allows assignment without a constructor call is a convenience. The content is stored in what amounts to static (read global) VM memory space.
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
The key concept to understand is the value of an object in Java is its reference, which is almost the same as c pointer except it can not be dereferenced.
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
Another thing interesting in Java is you can not put your hand on an object without through its reference.
On the contrary, in c/c++, you can.
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

Let me go ahead and ask this question. Should I REALLY be concerned with this? I mean, when I develop an application, is memory usage a concern, or since we have the Garbage Collector, we don't need to concern ourselves with it.
I bring up Gargabe Collector as a point, not a discussion topic...
Thanks

------------------
Happy Coding,
Gregg Bolinger
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
To Michael:
Can you go to Unix/Linux forum, and give me a hand there about the PID stuff.
It will be most appreciated.
Roseanne
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
Gregg
Yes, definitely, read here http://industry.java.sun.com/javaone/99/pdfs/e618.pdf
Roseanne
Michael Ernest
High Plains Drifter
Sheriff

Joined: Oct 25, 2000
Posts: 7292

On my way, RZ.
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Originally posted by Gregg Bolinger:
OK, so now I have heard both answers. And so appearntly no one REALLY knows what is going on.
Oh, I think most of the participants in this thread know extremely well what is going on. They are just using different words and perspectives to describe the same thing - we're knee-deep into mere semantics and arguing whose words are better, with some pretty absolutist statements having been made already. It looks like a technical discussion, but it isn't. It's about words.
The "pass-by-value" viewpoint is most popular with those who have a C/C++/Pascal/any other language with pointers background. They know that a variable with an non-primitive type (the JLS, significantly, calls that a reference type) is actually just a pointer (reference) to the real thing. This pointer is passed by value. No-one will argue about that.
The "pass-by-reference" viewpoint is most popular with those who have learned programming using the Java language or another language which doesn't expose pointers. Especially if they learnt it from overly purist sources which want to avoid the pointer concept altogether. If you think of method argument as the object (rather than a pointer) being passed, then that object is clearly being passed by reference. No-one will argue about that either.
You pass the object by reference. You pass this reference by value. They are two valid statements about one and the same thing. Heck, C++ even supports these two viewpoints at the language level (* for pointers vs & for references) even though they compile down to the same machine code. "Programming language theory" has nothing whatsoever to do with it. Human language practice has, as has human thinking.
And no one can show me a certified link on java.sun.com that just says it one way or another in plain english.
Sigh; I guess your confusion is unavoidable. Gregg, despite appearances we are not disagreeing about what is happening on a technical level. We are discussing how we ought to be talking about it.
But if you want Sun's words, the JLS uses the "pass-by-value" viewpoint. In the second link I included, it discusses the concept of "reference types" (classes and interfaces). As the name implies a variable of a reference type is discussed in terms of a pointer to the object on the heap. These references are then, obviously, passed by value in method calls (as discussed in the third link). It makes sense for the JLS to take this viewpoint because it is the more low-level view that closely corresponds to what happens in the JVM at the bytecode level. But at the Java language level you're perfectly fine to forget all about pointers and think in terms of objects that are passed by reference, if that suits you better.
- Peter
(Who once wrote a C compiler in a previous life - so, unsurprisingly, is a pass-by-value man)
[This message has been edited by Peter den Haan (edited October 19, 2001).]
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

Thank you very much Peter. I don't know if what you said made more sense this time, or that the amount of reading I've done the past couple of days just made me understand it better. But I appreciate all your help and patients.
To Everyone, Thank you ver very much.

------------------
Happy Coding,
Gregg Bolinger
Chris Perkins
Greenhorn

Joined: Mar 26, 2001
Posts: 9
Gregg:
Just to be sure that you are clear - when you said the following:
"Should I REALLY be concerned with this? I mean, when I develop an application, is memory usage a concern, or since we have the Garbage Collector, we don't need to concern ourselves with it."
It appears that your interest in this matter comes, at least partially, from a concern that passing an object to a method creates a complete copy of it, thus using up more memory.
I hope it has now been made clear that this does not happen - even the advocates of the "pass by value" terminology have stated that it is only the reference, and never the object itself, that is copied.
Chris
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
Originally posted by Chris Perkins:
I hope it has now been made clear that this does not happen - even the advocates of the "pass by value" terminology have stated that it is only the reference, and never the object itself, that is copied.

Precisely, thanks!

[This message has been edited by Roseanne Zhang (edited October 20, 2001).]
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
Peter
You are certainly good at redefining things, even including someone's previous life.
A debate starts here:
<pre>
R: How do you know my previous life?
P: You don't know it either, how do you prove I'm wrong?
R: At least I know in my previous life, C language has not been invented yet.
P: Your previous life is redefined as before you switched to Java.
R: I never wrote a C compiler, but a toy Pascal compiler using C.
P: That is close enough, since they both use pointers. C can be redefined as languages using pointers.
R: Ok, you win!
</pre>
Seriously, pass-by-value and pass-by-reference have their different definition in programming language theories. They are not the same thing. Don't confuse people by using a special case, which happens to be Java.
If you view Pass-object-reference-by-value as Pass-object-by-reference in Java, it does not hurt anything. They are almost equivalent. But they are not the same as Dr. James Gosling said.
Java is not going to dominate the world, neither c/c++, nor Microsoft. People will programming in different languages. You'd better keep your view on this issue in your office or cube, since it does not hurt anything. However, don't spread it, please! Of course, this is only my suggestion.
We certainly will agree to disagree one more time.
Thanks!
Roseanne
[This message has been edited by Roseanne Zhang (edited October 20, 2001).]
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Originally posted by Roseanne Zhang:
Seriously, pass-by-value and pass-by-reference have their different definition in programming language theories. They are not the same thing.
Who's redefining things now? I never said this. But, "Reference mode can be emulated by value mode if the language has a reference operator [...] which produces a pointer to an expression with an L-value, and a dereferencing operator [...]" (Finkel, Advanced Programming Language Design). It is this equivalence which supports both viewpoints. If applied consistently, of course.
Gosling's remark means something different even though it mostly uses the same words (I warned these discussions were mired in semantics, didn't I?) It is informed by the wider context of his discussion, where objects types are firmly put on the map as reference types because that is the only way to make sense of things like Java's object assignment and garbage collection. The distinction made between "objects passed by reference" or "object references passed by value" is in fact the distinction between "an object variable contains the object" and "an object variable contains an object reference". Obviously, the former is patently false.
This, however, is subtly different from my wording at the start of this whole sorry "discussion". I stated that objects, as objects, are passed by reference, which is entirely true - note the stress put on the objects themselves rather than the variables (or expressions) referring to them, which was intended precisely to make the meaning unambiguous. My apologies if it was not clear enough.
You'd better keep your view on this issue in your office or cube, since it does not hurt anything. However, don't spread it, please! Of course, this is only my suggestion.
Mmmmm. Don't you think that's a rude and derogative way to finish off a discussion? I'll respectfully decline if you don't mind.
Agreeing to disagree is something only possible in matters that to a greater or lesser extent involve taste. In this case, either one of us is simply wrong, or we do not properly understand each other. To me, you have just confirmed that the latter is true. So I'll agree to agree.
- Peter

[This message has been edited by Peter den Haan (edited October 21, 2001).]
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Upon reflection, my choice of words has been inept and imprecise in places, which is unforgiveable in a written medium like this. I wanted to avoid a discussion about semantics, but it looks like I achieved the opposite.
Thanks, Roseanne. One certainly has to stay on one's toes around you
- Peter

[This message has been edited by Peter den Haan (edited October 22, 2001).]
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

The terminology pass-by-reference is invalid in Java, period. NOTHING in java is ever passed-by-reference. period.
There is no alternate way of looking at it.
Variables are passed, objects are not. Thus arguing over how objects are passed is meaningless since objects are NOT passed. This is a major source of confusion.
Variables are _always_ copied when they are passed. (by-value)
Some variables happen to refer to objects. That does not change anything.
There is NO room for exception There is no basis for arguement.
Objects spend their whole lives on the heap. They do not move. They do not "pass" go(). They never touch the stack. They never are found inside a method no matter how you fabricate it.

Now contrast this to C++ where objects can live on the stack. And you normally pass references to things just as in c. But in c++ when you are doing the "pass-by-reference" what you are actually doing is passing the "variable" by reference, not the object. And in effect you pass a reference to a reference to an object.
In c this was achieved like so


[This message has been edited by CL Gilbert (edited October 23, 2001).]
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

Sir, Yes Sir!!!
------------------
Happy Coding,
Gregg Bolinger
vicky bawge
Ranch Hand

Joined: Sep 04, 2001
Posts: 34
I agree that everything is passed by value in java. But, everything is a reference in java. So, everything is passed by reference in turn. Because copy of reference is again pointing to the same object. So, obviously, any manipulation to the object pointed by copy of reference affects the original reference.
The best visualsation of reference in java is the const pointer in c++
Any comments,
Vivek
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

I have stopped reading the responses in this discussion. Once again, no one can agree on the answer to these questions. And maybe there is no right or wrong answer.
Thanks for all of your help on the topic though. I will just have to research this one a lot more.
Thanks Again!!

------------------
Happy Coding,
Gregg Bolinger
Chris Perkins
Greenhorn

Joined: Mar 26, 2001
Posts: 9
I want to stop reading them too, but it's kind of like watching a train wreck, isn't it? Too gory not to look...
Keep in mind though, that everyone posting here, without exception, is in complete agreement about HOW java actually does things - the ONLY thing being debated is the appropriate words to use to use to describe it - and in my mind, that's pretty much irrelevant to 99% of Java coders. As long as you understand HOW it works, it doesn't matter much which words you use to describe it.
Chris
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
CL
You are correct on Java, everything is passed-by-value.
However, you are not correct on C.
<pre>void func(int **value); // compile in both c/c++</pre>
This is still passed-by-value, the value of a pointer of pointer of an int. If you dereference it inside the function, you will never get the same address as you dereference it from outside, since it is a copy inside. Try it, you will see what I meant. C++ allows passed-by-reference
<pre>void func(int &(*value)); // only compile in c++</pre>
Try it again, please.
However, in Java, you have no way to dereference it, that is why I said there was an equivalent view.
This topic is confusing enough for a lot of experienced programmers, let alone novices. We'd better stick to what Sun or Dr. Gosling said to avoid confusing more people.
I'll stop right here, no matter there might be more flame on Java or C or C++. I'm quitting!!!
Thanks!
Roseanne
[This message has been edited by Roseanne Zhang (edited October 25, 2001).]
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Originally posted by Roseanne Zhang:
CL
You are correct on Java, everything is passed-by-value.
However, you are not correct on C.
<pre>void func(int **value); // compile in both c/c++</pre>
This is still passed-by-value, the value of a pointer of pointer of an int. If you dereference it inside the function, you will never get the same address as you dereference it from outside, since it is a copy inside. Try it, you will see what I meant. C++ allows passed-by-reference
<pre>void func(int &(*value)); // only compile in c++</pre>
Try it again, please.

You are wrong.
passing this

Will allow you to change what x is equal to since you have the exact address of x.
passing this

will allow you to change what x points to completely since you have the address of the pointer which holds the address of x. This is what "pass by reference" allows you to do. And that is how it is done in c.
in Java we do it like this

This will allow x to receive a new value. its the c trick. its not like what you do in c++, but its a simulation, just like the c version.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Passed By Reference?