This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "help !" Watch "help !" New topic

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();
public void amethod(){
int i = 99;
ValHold v = new ValHold();
System.out.println(v.i);//why it prints 20
}//End of amethod
public void another(ValHold v, int i){
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

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

Joined: Nov 01, 2000
Posts: 51
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="" target="_blank" rel="nofollow"></a> Real Estate, Tampa Florida
I agree. Here's the link:
subject: help !
It's not a secret anymore!