Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer parameter passing.

 
Suresh Rajadurai
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 580
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Suresh Rajadurai
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 580
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic