This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
1. You are passing a reference of object v to the method "second". 2. You are setting its "i" member variable to 20 3. You are setting v reference to a new reference, but remember that eveything in java is passed by value. So even if you assign v to a new reference, it won't change outside the method. 4. In main, after calling "second", v's reference is still the same, so the ouput is 20.
You can try to check v's reference before and after calling "second", with System.out.println(v)
First of all, when you post code, please put it between [code] ... [/code] tags, so that the forum software automatically formats it.
What output did you expect, why do you think 20 is strange?
Arguments to methods are passed by value in Java. That means that not the variable itself is passed, but just the value of the variable, copied into a new variable. With primitives like int this is easy to understand.
Note that the variable v in your method called first() is a reference variable. It points to an object of type Value. When you pass v to the method named second(), you pass the reference to the object by value. In the method second(), there is a new variable called v, which is a copy of the v in the method first(). Note that the object that v points to is not copied, only the reference to the object is copied, so that v in second() points to the same object as the v in first()!
So if you change anything to the Value object that v in second() points to, it changes also in the Value object that the v in first() points to - because it's the same object.
So if you set v.i in second() to 20, you'll see the change also in the method first().
[ August 29, 2006: Message edited by: Jesper Young ] [ August 29, 2006: Message edited by: Jesper Young ]