Hi,
There is a concept of passby value and passby reference. When
you pass a primitive type it is passed by value. What i mean
by this is a copy of the original parameter is passed to the
function. Now lets supposed
main()
{
int a = 7;
somefunction(a);
}
somefunction(int b)
{
print(b);
}
In this case a copy of the value of a which happens
to be 7 is passed to the function somefunction.
ie there are two different symbols a and b which
have the same value 7.
But when u pass an object it is pass by reference.
By this i mean that the location (address) where the
object resides is being passed to the function. So once
i get the address in the function i can look into that object and
modify it contents.
main()
{
Object obj;
somefunction(obj);
}
somefunction(Object localobj)
{
int newValue = 10;
localobj.val = newValue;
}
Thats what u are doing with your
v.i=20. So effectively you are changing the contents
of the object. Since obj and localobj are looking
at the same address.
But then when you assign the localobj with a new
obj then localobj will now look(point) to a different
location(address). (Please remember the original object is still
in place). You are just making your localobj to point to
some other object ie location/address.
ValHold v = new ValHold();
And now whatever you do with this local object is local to you function.
Infact it will be garbage collected once you return from you function
since it is no longer in the scope.
Hence before the assignment
ValHold v = new ValHold;
there is only one object under consideration which is being modified and after
the assignment there are two completely independent object and you
are looking at the newly created one.
I hope you understand this. Iam sorry about the syntax since iam not quite
particular about it and also iam still not comfortable with
Java (Iam
from a C/C++ background)
RK