StringBuffer is a class in Java whose object represents the mutable string. It is just like a string class except that its object can be modified. StringBuffer is synchronized, hence it is thread-safe.
i.e. StringBuffer class objects are thread-safe, mutable sequences of characters.
For these reasons, Java would handle an expression like
String newString = aString + anInt + aChar + aDouble;
like this:
String newString=(new StringBuffer(aString)).append(anInt).append(aChar).append(aDouble).toString();
Note: StringBuffer does not override the equals method of the object class, so StringBuffer objects should be converted into string objects if you want to compare StringBuffer class objects.
Constructors of StringBuffer class.
- public StringBuffer(): creates a string buffer with no characters and with a default capacity of 16 i.e. it can contain 16 characters.
- public StringBuffer(int capacity): creates a string buffer with no characters and with specified capacity.
Note: capacity should not be less than zero, otherwise it will throw NegativeArraySizeException. - public StringBuffer(String str): creates a string buffer with a specified string as initial content.
Initial capacity = Default capacity + length of the string.
Note:
1. string should not be null otherwise it will throw NullPointerException.
2. if the string length is equal to zero then the string buffer with no content and default capacity is returned. - public StringBuffer(CharSequence charSquence): creates a string buffer with a specified character sequence as its initial content.
Note:
1. charSquence should not be null otherwise it will throw NullPointerException.
2. if the char sequence length is equal to zero then the string buffer with no content and default capacity is returned.
Commonly used methods of StringBuffer class.
S.No. | Method | Description |
 1. | append(String str) | Append the specified string at the end of this string. |
 2. | insert(int offset, String str) | Insert the specified string at the offset indicated position. |
 3. | replace(int startIndex, int endIndex, String str) | Replace the substring of the string buffer from startIndex to endIndex-1 with the specified string. |
 4. | delete(int startIndex, int endIndex) | delete the substring of the string buffer from startIndex to endIndex-1. |
 5. | reverse() | replace the string buffer’s character sequence with a reverse character sequence. |
 6. | capacity() | returns the current capacity of the string buffer. Capacity refers to the amount of available storage. |
 7. | ensureCapacity(int minCapacity) | ensures that the capacity is at least equal to the specified minimum. |