• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain me ? StringBuffer

 
Pankaja Shinde
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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");
method(sb);
System.out.println(sb);
}
}

What is output?

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

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

Please explain me ?

Regards

Pankaj Shinde
 
Freddy Wong
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
subodh gupta
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic