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?
Joined: May 15, 2001
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.
Joined: Oct 12, 2000
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).
Joined: Sep 15, 2004
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.