wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes help ! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "help !" Watch "help !" New topic
Author

help !

Rajeev Nair
Ranch Hand

Joined: Mar 11, 2002
Posts: 51
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


Raj<br />Sun Certified Java Programmer
Mario Levesque
Ranch Hand

Joined: Nov 01, 2000
Posts: 51
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


<a href="http://www.ajmasters.com" target="_blank" rel="nofollow">http://www.ajmasters.com</a> Real Estate, Tampa Florida
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: help !
 
Similar Threads
urgent pls explain
Tricky question
passing param
urgent pls explain
why is the output ........