This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings and StringBuffers

 
Varghese Paul
Greenhorn
Posts: 14
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read in a book that we should when not sure of size of string or during concatenation, it would be better if we must use StringBuffers. For example if we were adding two strings

String a="Hello";
String b="World";
//instead of using a=a+b or a=a+"World", where we have declared a as a
//string, we should have declared a as a type of StringBuffer and then
//should have called the a.append("WOrld") function.

Any specific reason?
 
Nigel Browne
Ranch Hand
Pie
Posts: 682
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java a string is immutable, so that even though it is legal to do the following

What is happening behind the scenes is that the java compiler is using the StringBuffer for concatenation. So the above actually compiles to

Strings should be used when ever you know in advance that the value will remain constant because they are more efficient than StringBuffers.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Strings aren't necessarilly more efficient than are StringBuffers. Some of their operations are faster or use less memory, but for others that's not the case (concattenation being the prime example).
 
Mahesh Bhatt
Ranch Hand
Posts: 88
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

Remeber that Strings are Immutable, that means once they are created they cannot be changed, however for our convenience, java makes strings into stringbuffers when we perform concatination. Eventough we are using strings, back there its actually stringbuffers. so why not use stringbuffers instead. Apart from that if you have a look at the various methods inside the stringbuffer class you would definately see that it is always better to use a stringbuffer when you are making lot of changes to a string.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic