• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

parameter passing

 
vinita Kh
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marcus Green test-II
y the answer is 4 not 2
if we r assigning v.i= 30 in amethod(), then in that method is should print its value as 30, even though we have passes this instance to some other method which modifies this by using this instance.
ne help?
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.print( 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.print(v.i);
System.out.print(i);
}//End of another
}
1) 10030
2) 20030
3) 209930
4) 10020
 
Gautam Sewani
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its a simple question.You pass v to another().In java,the references of Objects are passed.In another(),you modify the value of i of v.(v.i=20)
Then you change the value of v itself.But before that the value of i has been changed!
This changed is reflected in the original v as references of objects are passed,and changes made through that reference are reflected back in the original reference.
Therefore,the answer is 4.
Hope that helps
 
John Wetherbie
Rancher
Posts: 1449
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another way to put it is that in Java object references and primitives are passed by value. In the case of the object reference you can change the value of members of the object and these will be reflected outside the scope of the method (since what you have inside the method is a copy or alias). Changing what the object reference refers to will NOT be reflected outside the method.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at this Flash app. I built it to illustrate what is happening in this exact case.
I hope that helps,
Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic