Win a copy of Spark in Action this week in the Open Source Projects forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

help !

 
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
 
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
 
Blueberry pie is best when it is firm and you can hold in your hand. Smell it. And smell this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic