Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Passing of an object : example

 
Gary Peck
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please look at the code below.
The final print out when run is:
10,0
20
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();
o.amethod();
}

public void amethod(){
int i = 99;
ValHold v = new ValHold();
v.i = 30;
another(v,i);
System.out.println(v.i);
}

public void another(ValHold v, int i){
i=0;
v.i=20;
ValHold vh = new ValHold();
v=vh;
System.out.println(v.i+" " + i);
}
}
 
Avi Abrami
Ranch Hand
Posts: 1141
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
Avi.
 
Gary Peck
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
HTH
Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic