Two Laptop Bag
The moose likes Beginning Java and the fly likes Strings and StringBuffers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Strings and StringBuffers" Watch "Strings and StringBuffers" New topic

Strings and StringBuffers

Varghese Paul

Joined: Aug 02, 2004
Posts: 14
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

Joined: May 15, 2001
Posts: 673
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

Joined: Oct 12, 2000
Posts: 5093
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

Joined: Sep 15, 2004
Posts: 88
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.

Impossible is I M Possible
I agree. Here's the link:
subject: Strings and StringBuffers
jQuery in Action, 3rd edition