• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

help !

 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic