Author | Topic: StringBuffer |
Umesh ranch hand |
posted March 27, 2000 11:32 PM
Output: sb1 is HiUmesh My question is why not s1 assigns value to S2 in the code marked lineX and prints following output: Thanx in advance.
|
Frank Tamminga greenhorn |
posted March 28, 2000 12:15 AM
It looks quite weird doesn't it? But it is not that difficult. Method() takes two StringBuffer args. These are copies of the original references to the objects created in the body of main. In method() you change the object referred to as s1. Now you assign the temporal reference s1 to s2. When you leave method(), the original s2 still referres to the original object. I hope I cleared it out... [This message has been edited by Frank Tamminga (edited March 28, 2000).]
|
maha anna bartender |
posted March 28, 2000 10:20 AM
Umesh, I changed your code a little bit in order to provoke thinking. Can u tell what the result and your understanding for the same. regds maha anna
|
Umesh ranch hand |
posted March 29, 2000 09:13 PM
Hi Anna, Here is the output: My understanding: Incase of StringBuffer, its not immutable and original object can be modified thru reference. Thank you Frank and I need input from Maha Anna for my comments.
|
maha anna bartender |
posted March 29, 2000 09:29 PM
Umesh, In Java String objects are immutable. Meaning once created, it's content NEVER changes. But the StringBuffer object's content is changable. So for the 1st qstn which you posted used StringBuffer, when calls method1(StringBuffer sb1,StringBuffer sb2), after the method returns , the content of the originally passed StringBuffer is changed to "Hi Umesh". But when the same method is slightly modified to take String as an arg, after the method is called, eventhough we tried to concat the input arg String sb1 with "Umesh" inside the method(String sb1, String sb2), what happened inside the method was a NEW String object was created, and the original String object passed to this method was UNTOUCHED. This proves the immutablity of String object. You may find this particular discussion useful. regds [This message has been edited by maha anna (edited March 29, 2000).]
|
| | |