• Post Reply Bookmark Topic Watch Topic
  • New Topic

String and StringBuffer  RSS feed

 
Ajit Shanbhag
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • 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?
 
Vijitha Kumara
Bartender
Posts: 4002
42
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String is immutable while StringBuffer is not. Here is an article at java world which discuss about it.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • 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
  • 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. [ ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!