Java StringBuffer is a sequence of characters like Java String. However, the difference being is StringBuffer is mutable while String is immutable. That means the StringBuffer object’s content can be changed or modified using its methods.
String buffer is thread safe, means that if multiple threads are trying to modify the content of the string buffer at the same time, the StringBuffer class takes care of the synchronization. It does that by doing the necessary synchronization of the methods.
The Java StringBuffer extends from Object class and implements Serializable, Appendable and CharSequence interfaces. It is contained in the java.lang package. The java.lang package is automatically imported into the code, so you do not have to import any package to use the StringBuffer class.
The StringBuffer class internally manages an array to store its contents. The length of this array is called StringBuffer capacity. The capacity of the StringBuffer is automatically increased as we add more content to it. It does it by allocating a new internal array with the required length.
Allocating a new array is a costly operation. If you know the approximate number the StringBuffer object is going to hold beforehand, you should create the big enough StringBuffer object with required capacity using below constructor.
public StringBuffer(int initialCapacity)
This will avoid the allocating and copying the content to the new internal array and will improve the performance of the code.
Below given are some of the very useful methods of the StringBuffer class.
1) The append method appends the specified content to the StringBuffer object. The append method is overloaded to accept the data of any type.
2) The insert method inserts the specified content to the StringBuffer object at the specified position. The insert method is also overloaded to accept the data of any type.
3) The charAt method returns the character located at the specified index of the StringBuffer object.
4) The delete and deleteCharAt methods delete the character(s) from the StringBuffer located at the specified index position(s).
5) The capacity method returns the current capacity (i.e. the length of the internal array) of the StringBuffer, while the ensureCapacity method ensures that the capacity of the StringBuffer is at least equal to the specified capacity.
6) The indexOf method returns the index of the first occurrence of the specified substring within the StringBuffer.
7) The reverse method reverses the content of the StringBuffer.
8) The substring method returns substring from the StringBuffer content located at the specified index positions.
9) The trimToSize method tries to reduce the storage used by the StringBuffer object. It does that by allocating a new array of the smaller capacity.
Below given are some of the Java StringBuffer examples which shows how to use StringBuffer in Java.