StringBuffer helps you reduce Java overhead

Dealing with dynamic string data requires care to avoid excessive system resource consumption. The basic Java StringBuffer class is designed to get the job done.

Working with text values is a routine developer chore, and the standard Java String class is often used to fulfill every text-related need. It is appropriate for many small tasks, but it can become a system resource hog when dealing with large values. For this reason, the StringBuffer class was included in the JDK to provide an efficient approach to dealing with strings. Let’s take a closer look at how you can use this class to improve performance.

Why avoid standard Strings?
Java String objects are constant strings. Once they are initialized and populated, the value and memory allocation is set. If the value changes in any way, a new object is created for the new value. That's why String objects can become a resource hog. The following code creates String objects and uses the concatenation (+) character to add more characters to them:
String sample1 = new String(“”);
sample1 += “ is “;
sample1 += “the place “;
sample1 += “to be.”;

In the end, the system creates four String objects to handle the alterations. The first is created with the text A new object is created every time more text is appended.

The problem with this approach is that too many resources are being used for such a simple procedure. The effects may be minimal in this instance (given the small amount of code), but a larger application with more operations will likely degrade performance. This is the niche filled by the StringBuffer class.

Processing strings with StringBuffer
The StringBuffer class is designed to create and manipulate dynamic string information. The memory allocated to the object is automatically expanded to accommodate additional text. There are three methods to create a new StringBuffer object: using an initial string, setting the size, and using the default constructor:
StringBuffer sb = new StringBuffer();
StringBuffer sb = new StringBuffer(30);
StringBuffer sb = new StringBuffer(“”);

The first line creates an object with no text and the default capacity of 16 characters. The second instance of the class has no value and a capacity of 30 characters, and the final line creates an object with the initial value. The StringBuffer class is included in the base java.lang package, so no special imports statement is needed to take advantage of it.

You can use numerous methods and properties of the StringBuffer class once the objects have been created. The most notable method is append, which allows you to add text to the end of the current contents of the StringBuffer object. The following code provides a look at the syntax of the append method:
StringBuffer sb = new StringBuffer();

This code creates the string and sends it to the standard output, but only one object is created. The same code using String objects would require more than eight objects. Notice that the code takes advantage of the toString method of the StringBuffer class. This method converts the contents to a String object that can be used for output. This allows text to be manipulated accordingly and used for output or data storage.

The append method has 10 overloaded formats allowing various data types to be added to the end of the object. The StringBuffer class also provides methods for working with data stored in the object.

StringBuffer capacity
You can use the capacity and length methods to work with the number of characters in the object. The capacity method returns the number of characters (memory) allocated for the object. If the capacity is surpassed, it is expanded to meet the demand. The length method returns the current number of characters stored in the object. The length may be increased with the setLength method. In addition, the capacity of the object may be set or expanded with the ensureCapacity method. This establishes the minimum capacity for the object, so it can be exceeded with no problems. The following code takes advantage of these methods:
StringBuffer sb = new StringBuffer();
sb.append(" is awesome!");

This code sets the capacity and populates the object with a string. The length property is reset so that the text is truncated. The output follows: is awesome!

Manipulating strings
More methods are available to work with the string values stored within the StringBuffer object. The following list provides a sampling:
  • CharAt returns an individual character from the string.
  • SetCharAt populates/replaces an individual character within the string.
  • GetChars returns a substring of the string.
  • insert inserts values into the string at a specified location. This has multiple overloaded versions to accommodate various data types.
  • substring returns a subset of the string.
  • reverse reverses the contents of the StringBuffer.

All of the methods are useful for manipulating values, but the reverse method is the coolest—it allows you to easily reverse a string with one call. The following code and output show it in action:
StringBuffer sb = new StringBuffer();

The StringBuffer advantage
String values are used throughout most applications, whether as labels for the user interface or behind the scenes when working with values retrieved from a database. Often, these values do not follow the requirements, so they must be manipulated. You can use the base String class, but it is not designed for dealing with dynamic data values. The StringBuffer class fills this need and makes effective use of system resources.

Editor's Picks