Sorry John - its quite a long winded response.
The key thing to remember is that java passes everything by value and
nothing by reference.
In this diagram (which I hope works on posting)each horizontal section represents a new set of values on the stack.
Objects are never passed to methods, only references to objects are passed to methods.
This is demonstrated in line 24 where the value held in "val", a reference to a new instance
of Value() is assigned to the reference variable "v". This results in "v" holding a
reference to the new instance of Value(). It does not have any impact on the
instance of Value() previously referenced by this local variable.
- first() has an int called i with a value of 5 and an instance of Value() called v.
- second() has another int also called i which is a parameter variable and so is assigned the value passed on the call. This int's value is subsequently changed to be 0 on line 21. There is also a parameter variable which is a reference to a Value() instance. This variable holds a reference to the instance of Value() created on line 13. On line 22 we use this reference variable to change the value of i held in the instance of Value() to be 20. On line 24 we then change the value of the reference variable to refer to a new instance of Value().
It is important to distinguish between references to objects and the objects themselves.
Something that is well illustraded by your code example.
I hope this helps,