File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Please explain me ? StringBuffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Please explain me ? StringBuffer" Watch "Please explain me ? StringBuffer" New topic

Please explain me ? StringBuffer

Pankaja Shinde
Ranch Hand

Joined: Sep 15, 2006
Posts: 87
Please explain me ? StringBuffer

public class Test15{
public static void method(StringBuffer sb){
sb.append(" Added");
sb = new StringBuffer("Hai");
public static void main(String a[]){
StringBuffer sb = new StringBuffer("String Buffer");

What is output?

1. String Buffer
2. String Buffer Added
3. Hai
4. Compiler Error

Answer : ------------
String Buffer Added

Please explain me ?


Pankaj Shinde
Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959

StringBuffer is mutable and thus when you call method(StringBuffer), the sb will become "String Buffer added".

The line

assigns sb with the new reference, but it will not make the sb becomes "Hai" because you only pass in the copy of the reference and not the original reference.

So, in conclusion, the answer is "String Buffer added".

Hope it's clear enough for you.

SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
My Blog
subodh gupta
Ranch Hand

Joined: Jul 23, 2007
Posts: 203
To add another prespective when you are calling the method you have passed the refrence pointing to the object in the main and appended it with string "Added".

Than you assigned new object to the refrence in the scope of the method therefore when you come out of the method's scope this object will be elligible for the GC and when you SOP in main it will print the value of the object created in the main and appended in the method call.

You can draw the object to make yourself clear or if you face any problem post it here.
[ October 04, 2007: Message edited by: subodh gupta ]
I agree. Here's the link:
subject: Please explain me ? StringBuffer
It's not a secret anymore!