• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Please explain me ? StringBuffer

 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
passwords must contain 14 characters, a number, punctuation, a small bird, a bit of cheese and a tiny ad.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic