StringBuilder and StringBuffer are Java’s way of introducing mutability in Strings. Sometimes we know in advance that a String will be mutated many times. In such a scenario, we may end up with a large number of immutable Strings, that need to be garbage collected. To avoid using immutable Strings in such a scneario, Java provides StringBuilder and StringBuffer. StringBuilder and StringBuffer are an implementation of the Gang-of-Four Builder Design-Pattern. These two classes are the same and achieve the same end result, except that all methods in StringBuffer are synchronized. Methods that are synchronized incur additional runtime penalty, so unless you are working in multi-threaded application you should prefer StringBuilder over StringBuffer.
Creating Instances of StringBuilder and StringBuffer
These builder classes, pretty much like char deal with individual characters. The only difference is that these classes know how to increase or decrease their capacity (size) and are aware of their length. Since these classes act on individual character, it is possible to add and remove characters at various positions. These classes behave like ordinary Java classes and are immutable.
Important Methods of StringBuilder and StringBuffer
The table below shows methods in both these classes that are used quite often
|append ( String s)||Takes a string parameter. Concatenates to the existing content. Prime example of mutability of StringBuffer/Builder.|
|append ( char c) , append ( boolean b) … etc.||Same as above. These methods add the parameter to the end of existing content|
|insert ( int offset, String s)||Insert the contents of string s at the position specified by offset. There are overloaded invariants that take float, boolean, double etc. instead of String s|
|replace( int start , int end, String s)||Replaces the contents from index start to index end by string s. This is the only valid form and is not overloaded|
|delete ( int start, int end)||Clears the contents from start to end|
|capacity()||Returns the current capacity. Empty objects start with value 16.|
|setCharAt (int index, char ch)||Modifies just one character at location index|
|length()||Returns the length as a character count|
|setLength(int newLength)||Used to increase or decrease the length. if new length is less than current, characters at the end are trimmed.|
Note that StringBuilder and StringBuffer have capacity in addition to length. A capacity is an integer indicating how many characters worth of memory has been allocated. A capacity 16 means that without any further changes to capacity, 16 characters can be stored.
A Simple Example of StringBuilder and StringBuffer
Here is a short snippet showing how append might be used to avoid creating multiple strings.