This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes StringBuffer problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "StringBuffer problem" Watch "StringBuffer problem" New topic

StringBuffer problem

rimzim sinha

Joined: Oct 26, 2004
Posts: 17
question from

Why is the output "String Buffer added" when String Buffer is assigned "Hai"
in the last line?

Pls explain
[ November 08, 2004: Message edited by: Barry Gaunt ]
Olivier Lambert

Joined: Apr 30, 2004
Posts: 9

When you enter in the method "method", there is only 1 object in memory (the one with the value "StringBuffer") but 2 references to this object (sb in the main andthe local variable sb in the method parameter).

Ref sb (from main method) ---> "StringBuffer"
Ref sb (from method method) ---> the same object

So when you call sb.append(...) in the method "method", it's the original object that is modified =>StringBufferAppend. At this time we have in memory:

Ref sb (from main method) ---> "StringBufferAppend"
Ref sb (from method method) ---> the same object

Then when you create a new object and assign it to sb, it is the local reference that is modified, not the reference from the variable of the main method. The result in memory is:

Ref sb (from main method) ---> "StringBufferAppend"
Ref sb (from method method) ---> "Hai"

So when you leave the method "method", the variable sb reference already the same object, that has been modified.

Hope it can help.

Oli,<br />SCJP
rimzim sinha

Joined: Oct 26, 2004
Posts: 17
Thanks for clearing my concepts!
Krishna Srinivasan
Ranch Hand

Joined: Jul 28, 2003
Posts: 1844

Thank you for your explanation Olivier Lambert.

Krishna Srinivasan
Spring Tutorials, OCAJP Mock Questions, 400+ OCPJP Mock Questions
Hai Le

Joined: Sep 22, 2004
Posts: 28
very nice explaination...!!
thanx bro

Step one step back to learn more thing..!!<br />Post to learn<br />learn from mistake<br />take whatever i understand...!!!<br /> <br />SCJP 1.4, Brainbench Java 1 & 2.<br />SCWCD 1.4 (preparing...!!)
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: StringBuffer problem
Similar Threads
doubt with StringBuffer
StringBuffer Doubt
Please explain me ? StringBuffer
String Buffer
confusion about stringbuffer