• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String and StringBuffer

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is quiet a common question.... Which is better between String and StringBuffer? The answer to this is generally StringBuffer but then why do we use String in most of our applications.. Can anyone please help me with this?
 
Bartender
Posts: 4116
72
Mac TypeScript Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String is immutable while StringBuffer is not. Here is an article at java world which discuss about it.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Ajit Shanbhag:
This is quiet a common question.... Which is better between String and StringBuffer? The answer to this is generally StringBuffer but then why do we use String in most of our applications.. Can anyone please help me with this?


No, the answer is not that StringBuffer is generally better than String. It totally depends on what you are doing. If you need to create a string by concatenating parts together, for example in a loop, it's much more efficient to use StringBuffer, to avoid creating many temporary String objects and unnecessarily copying the contents of String objects.

If you are using Java 5 or newer, you should prefer StringBuilder above StringBuffer. StringBuilder is a little bit more efficient than StringBuffer (because it doesn't contain synchronization logic, which isn't necessary most of the time).
 
Ajit Shanbhag
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jesper. This means that only in case of concatenation, StringBuffer holds the advantage whereas if we want to use simple string objects, String can be preferred to be more efficient. [ ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic