It's not a secret anymore!
The moose likes Beginning Java and the fly likes String and StringBuffer Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "String and StringBuffer" Watch "String and StringBuffer" New topic
Author

String and StringBuffer

Ajit Shanbhag
Greenhorn

Joined: Oct 15, 2008
Posts: 7
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?


Ajit Shanbhag
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3670

String is immutable while StringBuffer is not. Here is an article at java world which discuss about it.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Jesper de Jong
Java Cowboy
Bartender

Joined: Aug 16, 2005
Posts: 12929
    
    3

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).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Ajit Shanbhag
Greenhorn

Joined: Oct 15, 2008
Posts: 7
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. [ ]
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: String and StringBuffer
 
Similar Threads
StringBuffer question
byte [ ] to StringBuffer
classcastexception
StringBuffer and String returned from a method doubt
How many Object is created?