"StringBuffer" And "StringBuilder" Classes In JAVA

This is an article on "StringBuffer" And "StringBuilder" Classes In JAVA in Java.

Introduction

The instances of the String class represent a string that cannot be modified. If we do want to create modifiable strings because we are going to do lots of string manipulation, we should use the java.lang.StringBuffer and java.lang.StringBuilder classes.If we choose to do a lot of manipulations with String objects, we will end up with a lot of abandoned String objects in the String pool. Objects of type StringBuffer and StringBuilder can be modified over and over again without leaving behind a great effluence of discarded String objects.
A common use for StringBuffers and StringBuilders is file I/O when large, ever-changing streams of input are being handled by the program. In these cases, large blocks of characters are handled as units, and StringBuffer objects are the ideal way to handle a block of data, pass it on, and then reuse the same memory to handle the next block of data.

StringBuffer Class

StringBuffer is a peer class that provides much of the functionality of strings. It represents growable and writeable character sequences. They may have characters and substrings inserted in the middle or appended to the end.

StringBuilder Class

The StringBuilder class was added in Java 5. It has exactly the same API as the StringBuffer class, except StringBuilder is not thread safe. In other words, its methods are not synchronized. Sun recommends that you use StringBuilder instead of StringBuffer whenever possible because StringBuilder will run faster. So apart from synchronization, anything we say about StringBuilder's methods holds true for StringBuffer's methods, and vice versa.

StringBuffer Constructors

This class provides three constructors:

StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)

The constructor with no parameter is the default constructor which reserves room for 16 characters without reallocation. The second version accepts an integer argument that explicitly sets the size of the buffer. The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation. StringBuffer allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time. Also, frequent reallocations can fragment memory. By allocating room for a few extra characters, StringBuffer reduces the number of reallocations that take place.

We can create a string by passing the string value as an argument of the StringBuffer class constructor, as shown here:

Code:

StringBuffer sb = new StringBuffer("Hello Dear!");

We can also pass in a String reference as a variable:

Code:

String str = "Hello Dear!";
StringBuffer sb = new StringBuffer(str);

Methods of StringBuffer and StringBuilder Classes

All the methods of both the classes are similar except that StringBuilder methods are not thread safe.

int length( ) method

The current length of a StringBuffer or StringBuilder string can be obtained from the length() method.
For example,

The capacity of sb is 21 because room for 16 additional characters is automatically added.

void ensureCapacity(int capacity)

If we want to preallocate room for a certain number of characters after a StringBuffer
has been constructed, we can use ensureCapacity( ) to set the size of the buffer. This is
useful if we know in advance that we will be appending a large number of small strings to a StringBuffer.

void setLength(int nlength)

This method sets the new length of the current string buffer to nlength. If nlength is smaller than the length of the current string buffer, it is truncated. If nlength is greater than the current length, the null characters are added to the end of the string buffer.

public synchronized StringBuffer append(String s)

This method will update the value of the string that invoked the method by appending the contents of the string s to the invoking string object whether or not the return is assigned to a variable. This method will take many different arguments, including boolean, char, double, float, int, long, and others when String.valueOf( ) is called to obtain its string representation of the argument.
For example,

This method returns a StringBuffer object and updates the value of the StringBuffer object that invoked the method call. In both cases, a substring is removed from the original object. The starting index of the substring to be removed is defined by the first argument (which is zero-based), and the ending index of the substring to be removed is defined by the second argument (but it is one-based).

This method returns a StringBuffer object and updates the value of the StringBuffer object that invoked the method call. In both cases, the String passed in to the second argument is inserted into the original starting at the offset location represented by the first argument (the offset is zero-based). Again, other types of data can be passed in through the second argument (boolean, char, double, float, int, long, and so on).
For example,

This method returns a StringBuffer object and updates the value of the StringBuffer object that invoked the method call. In both cases, the characters in the StringBuffer are reversed, the first character becoming the last, the second becoming the second to the last, and so on.

This method replaces one set of characters with another set inside a StringBuffer object.The substring being replaced is specified by the indexes startIndex and endIndex. Thus,the substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned.

Comparison

A string created with the String class cannot be modified, whereas a string created with the StringBuffer class can be modified. The equals(…) method in the String class returns true if both strings are identical, while the equals(…) method in the StringBuffer class returns true only if both string references refer to the same string.Because the StringBuffer class, unlike the String class, is designed to be thread safe (i.e. multiple threads can use a StringBuffer string in a synchronized way), we pay some price in terms of performance. If we know that our application is only a single-threaded application, we can use the StringBuilder class (which has the same functionality as the StringBuffer class), which will somewhat improve the performance but will not guarantee synchronization.