StringBuilder
objects are likeString
objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations.Strings should always be used unless string builders offer an advantage in terms of simpler code (see the sample program at the end of this section) or better performance. For example, if you need to concatenate a large number of strings, appending to a
StringBuilder
object is more efficient.Length and Capacity
TheStringBuilder
class, like theString
class, has alength()
method that returns the length of the character sequence in the builder.Unlike strings, every string builder also has a capacity, the number of character spaces that have been allocated. The capacity, which is returned by the
capacity()
method, is always greater than or equal to the length (usually greater than) and will automatically expand as necessary to accommodate additions to the string builder.
StringBuilder
ConstructorsConstructor Description StringBuilder()
Creates an empty string builder with a capacity of 16 (16 empty elements). StringBuilder(CharSequence cs)
Constructs a string builder containing the same characters as the specified CharSequence
, plus an extra 16 empty elements trailing theCharSequence
.StringBuilder(int initCapacity)
Creates an empty string builder with the specified initial capacity. StringBuilder(String s)
Creates a string builder whose value is initialized by the specified string, plus an extra 16 empty elements trailing the string. For example, the following code
will produce a string builder with a length of 9 and a capacity of 16:StringBuilder sb = new StringBuilder(); // creates empty builder, capacity 16 sb.append("Greetings"); // adds 9 character string at beginningThe
StringBuilder
class has some methods related to length and capacity that theString
class does not have:
Length and Capacity Methods Method Description void setLength(int newLength)
Sets the length of the character sequence. If newLength
is less thanlength()
, the last characters in the character sequence are truncated. IfnewLength
is greater thanlength()
, null characters are added at the end of the character sequence.void ensureCapacity(int minCapacity)
Ensures that the capacity is at least equal to the specified minimum. A number of operations (for example,
append()
,insert()
, orsetLength()
) can increase the length of the character sequence in the string builder so that the resultantlength()
would be greater than the currentcapacity()
. When this happens, the capacity is automatically increased.StringBuilder Operations
The principal operations on aStringBuilder
that are not available inString
are theappend()
andinsert()
methods, which are overloaded so as to accept data of any type. Each converts its argument to a string and then appends or inserts the characters of that string to the character sequence in the string builder. The append method always adds these characters at the end of the existing character sequence, while the insert method adds the characters at a specified point.Here are a number of the methods of the
StringBuilder
class.
Various StringBuilder
MethodsMethod Description StringBuilder append(boolean b)
StringBuilder append(char c)
StringBuilder append(char[] str)
StringBuilder append(char[] str, int offset, int len)
StringBuilder append(double d)
StringBuilder append(float f)
StringBuilder append(int i)
StringBuilder append(long lng)
StringBuilder append(Object obj)
StringBuilder append(String s)Appends the argument to this string builder. The data is converted to a string before the append operation takes place. StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)Deletes the specified character(s) in this string builder. StringBuilder insert(int offset, boolean b)
StringBuilder insert(int offset, char c)
StringBuilder insert(int offset, char[] str)
StringBuilder insert(int index, char[] str, int offset, int len)
StringBuilder insert(int offset, double d)
StringBuilder insert(int offset, float f)
StringBuilder insert(int offset, int i)
StringBuilder insert(int offset, long lng)
StringBuilder insert(int offset, Object obj)
StringBuilder insert(int offset, String s)Inserts the second argument into the string builder. The first integer argument indicates the index before which the data is to be inserted. The data is converted to a string before the insert operation takes place. StringBuilder replace(int start, int end, String s)
void setCharAt(int index, char c)Replaces the specified character(s) in this string builder. StringBuilder reverse()
Reverses the sequence of characters in this string builder. String toString()
Returns a string that contains the character sequence in the builder.
Note: You can use anyString
method on aStringBuilder
object by first converting the string builder to a string with thetoString()
method of theStringBuilder
class. Then convert the string back into a string builder using theStringBuilder(String str)
constructor.An Example
TheStringDemo
program that was listed in the section titled "Strings" is an example of a program that would be more efficient if aStringBuilder
were used instead of aString
.
StringDemo
reversed a palindrome. Here, once again, is its listing:Running the program produces this output:public class StringDemo { public static void main(String[] args) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); char[] tempCharArray = new char[len]; char[] charArray = new char[len]; // put original string in an array of chars for (int i = 0; i < len; i++) { tempCharArray[i] = palindrome.charAt(i); } // reverse array of chars for (int j = 0; j < len; j++) { charArray[j] = tempCharArray[len - 1 - j]; } String reversePalindrome = new String(charArray); System.out.println(reversePalindrome); } }To accomplish the string reversal, the program converts the string to an array of characters (firstdoT saw I was toDfor
loop), reverses the array into a second array (secondfor
loop), and then converts back to a string.If you convert the
palindrome
string to a string builder, you can use thereverse()
method in theStringBuilder
class. It makes the code simpler and easier to read:Running this program produces the same output:public class StringBuilderDemo { public static void main(String[] args) { String palindrome = "Dot saw I was Tod"; StringBuilder sb = new StringBuilder(palindrome); sb.reverse(); // reverse it System.out.println(sb); } }Note thatdoT saw I was toDprintln()
prints a string builder, as in:becauseSystem.out.println(sb);sb.toString()
is called implicitly, as it is with any other object in aprintln()
invocation.
Note: There is also aStringBuffer
class that is exactly the same as theStringBuilder
class, except that it is thread-safe by virtue of having its methods synchronized. Threads will be discussed in the lesson on concurrency.