hmehta,
Java programs do not deal directly with objects, but rather with object references. You can think of an object reference as the unique identifier of an object.
Like Core Java says, objects in java are always passed by VALUE.
This means that when you pass an object as an argument to a method, you actually pass a COPY of that object's reference. If you try to change this reference inside your function, the changes will be lost as soon as your function returns. This is because you really only changed the COPY of the original reference.
However, if you use the copy of the object reference to make changes to the object's members inside your function, these changes will exist after your function returns. Below is a small program to illustrate these points:
class
Test {
StringBuffer theBuffer;
Test()
{
theBuffer = new StringBuffer("original string");
}
void reassignBuffer(StringBuffer s)
{
s = new StringBuffer("the buffer from reassignBuffer");
}
void changeObjectViaRefValue(StringBuffer s)
{
s.append(" plus some stuff");
}
public static void main(
String args[])
{
Test myTest = new Test();
System.out.println("Before any methods called, theBuffer = " +
myTest.theBuffer);
myTest.reassignBuffer(myTest.theBuffer);
System.out.println("After call to reassignBuffer, theBuffer = " +
myTest.theBuffer);
myTest.changeObjectViaRefValue(myTest.theBuffer);
System.out.println("After call to changeObjectViaRefValue, theBuffer = " +
myTest.theBuffer);
}
}
When we start, theBuffer = "original string";
We call reassignBuffer() with a COPY of this object's reference. Inside reassignBuffer(), we try to make some changes to the argument. But because we are doing this to the copy, the changes don't stick after the method returns.
Next we call changeObjectViaRefValue() with a COPY of this object's reference. However, rather than trying to change the reference that we got as an argument, we make changes to the object that this reference points to. For this reason, the changes are still in effect after the method returns.
I hope this helps clear things up.
Stephanie