• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcus Green Exam 2, Question #51

 
jake noi
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
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
}
Could anyone explain how can we get 10,0,20? I think I know how to get 10,0. However, I'm quite confused about getting 20.
v = vh;
If the reference of v is at vh.
System.out.println(v.i);
Should it be 10? Thank you for your clarification in advance
Thank
Jake
 
Rob Acraman
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, Marcus is correct.
Remember that, in Java, arguments are always passed by value, not by reference. That means that altering the value of 'v' in "another" does not change the value of 'v' in "amethod".
So, amethod's 'v' is still pointing to its original object, which has had its 'i' member set to 20 in "another".
Hope this helps.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic