File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Passing of an object : example Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Passing of an object : example" Watch "Passing of an object : example" New topic

Passing of an object : example

Gary Peck

Joined: Jun 03, 2003
Posts: 15
Please look at the code below.
The final print out when run is:
This is confusing to me becasue it seems to me that when v=vh occurs, the object v should be changed, yet for some reason the final print of v.i is 20 and not 10.
Can someone explain?

public class ObParm {
public static void main(String[] args) {
ObParm o = new ObParm();

public void amethod(){
int i = 99;
ValHold v = new ValHold();
v.i = 30;

public void another(ValHold v, int i){
ValHold vh = new ValHold();
System.out.println(v.i+" " + i);
Avi Abrami
Ranch Hand

Joined: Oct 11, 2000
Posts: 1141

Hi Gary,
This may be difficult for me to explain via the forum, but anyway...
In method "amethod()", "v" is a variable. It holds the memory address of where the actual "ValHold" object is located. When you invoke method "another()", the computer creates a new variable (for the method parameter) and copies the value of variable "v" into the new variable (i.e. method parameter).
We now have two variables that both point to the same memory address. Therefore, in method "another()", before you create the new "ValHold" object, any use of the method parameter changes the object that the variable (from the invoking method -- "amethod()") refers to (hence people often talk about "object references" when dealing with java).
However, once you assign the method parameter to a new "ValHold" object -- via this line (in method "another()"):

you are no longer manipulating the object that the variable refers to. Therefore, the value of the "i" member, in the object referred to by the variable, does not change.
I hope this was clear to you.
Good Luck,
Gary Peck

Joined: Jun 03, 2003
Posts: 15
Thanks Avi...that clears it up. If I understand correctly, when the code v=vh occurs, the v that is now referencing the vh object, is actually just the method parameter variable switching from the original v object and now referencing the vh object. The confusing part that is now clear is that the actual method variable in amethod() is still pointing to the original v object...thus the value of 20 rather than 10.
Thanks again!
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
To help keep this clear, you should think of BOTH v and vh as references, NOT objects. When you assign v=vh, the reference is copied, not the object itself.

Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: Passing of an object : example
It's not a secret anymore!