• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question about passing parameters by value or by reference

 
dragon ji
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can understand this question:
class ValHold{
public int i = 10;
}
public class ObParm{
public static void main(String argv[]){
ObParm o = new ObParm();
o.amethod();
}
public void amethod(){
ValHold v = new ValHold();
v.i=10;
System.out.println("Before another = "+ v.i);
another(v);
System.out.println("After another = "+ v.i);
}//End of amethod
public void another(ValHold v){
v.i = 20;
System.out.println("In another = "+ v.i);
}//End of another
}
The output from this program is
Before another = 10
In another = 20
After another = 20
but another question:
class ValHold{
public int i = 10;
}
public class ObParm{
public static void main(String argv[]){
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);
}//End of amethod
public void another(ValHold v, int i){
i=0;
v.i = 20;
ValHold vh = new ValHold();
v = vh;
System.out.println(v.i+ " "+i);
}//End of another
}
I thinkd the output should be "10,0,10",
but why the real output is "10,0,20"?
 
Kamal Kishore
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The output "10,0,20" is justified.
In this whole flow, two objects of ValHold() have been created
one in amethod() - object1(say)
and one in another() - object2(say)
Now in total there are three references(handles) to these two objects.
1. reference v in amethod() - pointing to object1
2. reference v in another() - intially pointing to object1, and afterward pointing to object2
3. reference vh in another() - pointing to object2
Now let's see how the flow goes :
amthod() execution
1. object1 is created and modified with new i value of 30 with handle v
another() execution
2. reference v of another() method modifies object1 with i = 20
3. object2 is created with default value of i=10
4. refernce v of another() points to object2 now
5. i value of object2 is printed (which is 10)
6. local variable i is printed (which is 0)
amethod()
7. reference v of amethod() is still pointing to object1 whose current i value is 20
i value of object1 is printed (which is 20)
Conclusion:
Java does manipulate objects by reference, and all object variables are references.
However, Java doesn't pass method arguments by reference; it passes them by value.
hope that helps !
Kamal
 
dragon ji
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok,I get it now.thanx.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic