We will find an answer for the following questions
- What is StringBuffer
- Available Constructors
- Commonly used methods
- Java StringBuffer class is used to create a mutable (modifiable) string.
- The StringBuffer class in java is the same as the String class except it is mutable i.e. it can be changed.
- The Java StringBuffer class is the same as the StringBuilder class except that this one is synchronized.
- So its thread-safe and can be used if Object is shared among multiple threads.
- If sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(), x).
// creates an empty stringBuffer with the initial capacity of 16.
StringBuffer str = new StringBuffer();
// creates a stringBuffer with the specified string.
StringBuffer str = new StringBuffer("Hello World");
// creates an empty stringBuffer with the specified capacity as length.
StringBuffer str = new StringBuffer(40);
Common used Methods
// used to append the specified string with this string.
// The append() method is overloaded like append(char),
// append(boolean), append(int), append(float), append(double) etc.
str.append(" from India");
// reverse the order of characters
// Convert to String
String data = str.toString();
// return the length of the string
// clears object
str = new StringBuffer();