Introduction:
Exercise extra caution when choosing a technique for string concatenation in Java™ programs. Simply using the "+=" operator to concatenate two strings creates a large number of temporary Java objects, since the Java String object is immutable. This can lead to poor performance (higher CPU utilization) since the garbage collector has additional objects to collect. Use the Java StringBuffer object to concatenate strings because it is more efficient.
Recommendation:
String concatenation using the "+" operator creates many temporary objects and increases garbage collection. Using the StringBuffer class is more efficient.The servlet code sample shows how this can be implemented. Lab tests have shown up to a 2.3X times increase in throughput using StringBuffer class over the immutable String class.
The StringBuffer class represents a mutable string of characters. Unlike the String class, it can process text in place. Instead of the "+=" operator, the StringBuffer uses the append method, as shown below:
res.setContentType("text/HTML");
PrintWriter out = res.getWriter();
String aStudent = "James Bond";
String aGrade = "A";
StringBuffer strBuf = new StringBuffer();
strBuf.append(aStudent);
strBuf.append("received a grade of");
strBuf.append(aGrade);
System.out.println (strBuf);
Alternative
The String class is created by the Java compiler when it encounters characters contained within double quotes in an object. The String class is immutable; there are no methods provided that allow you to manipulate the contents of the string once it is created. Methods that operate on a string return a new string not an updated copy of the old one.
You can concatenate a string to create a dynamic string of data to be used in a println statement. In this example, several additional String objects are created. The "+=" operator is used to concatenate strings in this servlet example:
String typical_string;
Res.setContentType("text/HTML");
PrintWriter out = res.getWriter();
String aStudent = "James Bond";
String aGrade = "A";
typical_string += aStudent;
typical_string += "received a grade of ";
typical_string += aGrade;
System.out.println (typical_string);