| Author |
StringBuffer parameter passing.
|
Suresh Rajadurai
Ranch Hand
Joined: Feb 22, 2007
Posts: 58
|
|
Hi Gurus, I have a problem in the following code. Why, the output produced in "line 3" and "line 4" are not same. Even though the S1 is getting assigned the value of S2 in "line 2", why , this is not getting passed to "line 4". I always get confused with this parameter passing. Could you please explain me. Thanks in advance. Suresh.
|
 |
James Tharakan
Ranch Hand
Joined: Aug 29, 2008
Posts: 580
|
|
First thing to remember is that ,stringBuffer's methods dont create a new object(where as string create a new object when used with "+" operator.). before the call to the mybuff(), s1--> hello s2--> doing after the call,in the method, s1 and(s1) --> hello // (s1) is local variable s2 and (s2)--> doing // (s2) is local varaiable After append s1 and(s1) --> hello how are you s2 and (s2)--> doing After s1=s2 s1 --> hello how are you s2 and (s1),(s2)--> doing When method returns, s1 --> hello how are you s2 --> doing Hope you got it. And s1 of line 3 is local variable s1 at line 4 is not same as line 3 s1 [ December 02, 2008: Message edited by: James Tharakan ]
|
SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
|
 |
Suresh Rajadurai
Ranch Hand
Joined: Feb 22, 2007
Posts: 58
|
|
Hi James please explain me the following quote. Thanks you so much. Much appreciated.
After s1=s2 s1 --> hello how are you s2 and (s1),(s2)--> doing
Suresh
|
 |
James Tharakan
Ranch Hand
Joined: Aug 29, 2008
Posts: 580
|
|
After s1=s2 s1 --> hello how are you s2 and (s1),(s2)--> doing Before the assignment s1=s2(these two are local i.e scope is only within the method)local variable (s1) and s1 is refereing "Hello how are you". After assignment local varible(s1) is refering to doing(s2). But still s1 of the main is pointing to "Hello how are you". Hope you got it by now... If not change the local variable name .It would be clear to understand.
|
 |
Bill Shirley
Ranch Hand
Joined: Nov 08, 2007
Posts: 457
|
|
The object references are passed by-value not by-reference. Even if they are named the same, they are different variables in different scopes. The StringBuffer object the local variable is pointing to is mutable, and is changed in the method. So, it is still changed when the method returns, though the reference has gone out of scope.
|
Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
|
 |
 |
|
|
subject: StringBuffer parameter passing.
|
|
|