Wouldn't it be better to always use StringBuffer? When would I use one over another?
Right now I'm working with JavaBeans and factories. It would seem that Sring would be better used in the JavaBean, and maybe StringBuffer should be used in the Factory.
Any guidance from the experienced ranch hands?
When you need to pass an argument to a method named, say, setName(), the argument, presumably a "name", ought to be a String. When you need to return something from a method named, say, getName(), and it's supposed to return the "name" of something, then that method should return a String.
But let's say you have an array containing the names of the 50 states, and you need to loop over that array and build a comma-separated sentence like
"The 50 states are Alabama, Alaska, Arkansas..."
then you'll want to use a StringBuffer to accumulate the result, rather than using Strings and the "+" operator; it will be much more efficient.
( and author)
Be aware that StringBuffers have synchronized methods, which can be expensive. Accordingly, if you're not writing multithreaded code, consider using the StringBuilder class in Java 5.0.
Another noticeable point is :
* String CAN'T be modified (a process on a String will always return a new string as a result)
* StringBuffer CAN be modified (a process on StringBuffer really modifies the content of a StringBuffer)
You may look at the reasons here: http://java.sun.com/docs/books/tutorial/java/data/whytwo.html
The reason is here : Why two string classes ?
The conclusion is worth noting:
# Within a single string assignment, using String concatenation is fine.
# If you're looping to build up a large block of character data, go for StringBuffer.
# Using += on a String is always going to be less efficient than using a StringBuffer, so it should ring warning bells - but in certain cases the optimisation gained will be negligible compared with the readability issues, so use your common sense.