Hi Sudha,
i'll give it a try....
First i changed to code, used UBB and inserted a line numbering, so that i can refer to some numbers.
People told you String is immutable and StringBuffer is not. That's right, but from reading your questions i guess the problem is not between String and StringBuffer. It's more how parameters especially Objects are passed in Java.
Now step by step:
line 12: Here you create a String s, which is in the String pool
line 13: Here you create an Object of type StringBuffer. To be more precise, you have a variable sb, which is a reference to an object of type StringBuffer.
line 15: Now you call the method Change with parameters s (which is a String) and sb (which is a StringBuffer). Java passes parameters per value, meaning you get a copy of the original variable. Cause String is immutable, here you get a complete new String object. For StringBuffer, you will get a copy of variable sb, BUT this copy points to the same object.
line 3: Here we have a variable x pointing to a totally new String, and a variable y, which points to the same object as sb before.
line 5: Here you create a complete new String, cause Strings are immutable, so x is now another string, which has Java2 as value. On y, which is a reference to the original StringBuffer-Object, you append also 2. So y points now to a StringBuffer-Object which has value Java2.
line 8: Here the method ends, and all local variable are going out of scope. So x and y are no longer valid....
What have you done in this method?? You changed a local variable, which is out of scope at the end of the method -> x
You changed the original StringBuffer-Object over a
copy of the reference. y which is this copy is also out of scope at the end of the method, BUT the changes you made on the StringBuffer-Object are still valid.
line 16: The output will be: "String" followed by the value of s, which hasn't changed, cause all changes in method Change were made on a local base ->"Java", followed by "StringBuffer" and then followed by "Java2".
Hope that helps,
correct me if i'm wrong
cheers
Oliver
[This message has been edited by Oliver
Grass (edited November 16, 2000).]