USE STRINGBUFFER WHEN APPENDING TO STRINGS
In Java, Strings are immutable objects; that is, they cannot be
modified in any way after they are created. This means that when you
attempt to modify a String object, you are often doing much more work
than you might think.
For example, here is a simple and common method of concatenating values
together in Java:
String aString = "";
aString = aString+"a";
aString = aString+"b";
System.out.println(aString);
Because Strings are immutable, the old aString object has to be
discarded and a new aString object created every time a new string is
appended. In terms of both execution time and memory consumption,
object creation can be one of the most costly types of operations in
Java.
Compare that to the StringBuffer approach:
StringBuffer aBuffer = new StringBuffer();
aBuffer.append("a");
aBuffer.append("b");
System.out.println(aBuffer.toString());
By using a StringBuffer object, the appended strings are added directly
to the internal byte array of the StringBuffer rather than causing a
new String object to be allocated.
In general, if you find yourself appending values to a String more than
once in the lifetime of the String object, using a StringBuffer to
manage your changing values can improve the speed and efficiency of
your Java code.
------------------------------------------