Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help !

 
Rajeev Nair
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);//why it prints 20
}//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);//why it prints 10 for v.i
}//End of another
}

System.out.println (v.i+ " "+i);//why it prints 10 for v.iSystem.out.println(v.i);//why it prints 20
Thanks
 
Mario Levesque
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rajeev,
Long story short, you are passing a reference of an object to a method (here ref of v) then you changed the value of the instance variable of that object reference (to 20) still having the same first reference associated to v , then you initialise a second object (vh) which take the constructor value for its instance variable (10) and then you reassigne a new reference to the v object inside to the same reference as object (vh).
When the method returns the first object with the first reference still exist and it value is printed (20)
Please note that the v object inside the method is different than the v object before the call, the method call passes by reference.
try to understand what is happening to the references and you will get a better idea.
Note: the output occurs in this order:
10 0 //printed first from within the method call
20 //printed last when the method returns
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic