When u call a methos with objects as parmeters....u r actually passing a copy of the reference of the object...
So v in the in a method points to the object V and then u call the methiod another...by passing this reference....but what happens is that...
A copy of this is assigned to the first parameter of the method..this 'v' is local to this method...but both this 'v and the 'v' in the calling method point to the actual object..Now u modify the value to 20.
u create a new object which ahs an initial i value of 10. and copy the reference of this vh to v....remember this v is the local reference copy...the other v is still intact pointing to the original object.
now print...10 for v (pointing to vh objects..) 0 local value of i 20 (back in the calling method...the local copy of v perishes... and now the original unchange v pointing to the object...we have chanegd the val to 20 in the another method...have a look above for that)
CHeers to my colleagues who cleared it up for me...
Originally posted by VISHAL AGARWAL: Although v.i is assigned 20 in another(), after that statement v is made to point to vh whose i value is 10(default value).
A variable of object type -- a "reference variable" -- is a pointer to an object. Objects are independent of variables, and one variable can point to different objects at different times.
All Java method arguments are passed by value. That means that a copy of the variable is made, and that copy appears in the called method. If you pass a reference variable to a method, a copy of the pointer is made. Then you have two pointers pointing to the same object: one in the caller, and one in the called method.
In your program, you pass a ValHold reference variable to "another()". In another(), "v" initially points to the same same object as does "v" in "amethod()". Two different variables -- coincidentally, with the same name -- are both pointing to the same object.
Now, in another(), first a change is made to that one shared object through another()'s copy of the pointer to that object. Then the copy of "v" is made to point to a new object. Back in "amethod()", the original "v" still points to the original object.
another() then modifies the new object and prints two values.
Back in amethod(), the original "v" still points to the original ValHold object -- the one that another() modified when it was first called. That object's i is 20, so that's what is printed.
Read this for another explanation of the same concept.