StringBuffer in java
StringBuffer is a class in java whose object represents the mutable string. It is just like 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 sequence of characters.
For these reasons, Java would handle an expression like
String newString = aString + anInt + aChar + aDouble;
String newString = (new StringBuffer(aString)).append(anInt).append(aChar).append(aDouble).toString();
Note: StringBuffer not override equals method of object class, so StringBuffer objects should be converted into string objects if you want to compare StringBuffer class objects.
Constructors of StringBuffer class.
1. public StringBuffer():creates a string buffer with no characters and with default capacity 16 i.e. it can contain 16 characters.
2. 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.
3. public StringBuffer(String str):creates a string buffer with specified string as initial content.
Initial capacity = Default capacity + length of the string.
1. string should not be null otherwise it will throw NullPointerException.
2. if string length is equal to zero than string buffer with no content and default capacity is return.
4. public StringBuffer(CharSequence charSquence):creates a string buffer with specified character sequence as its initial content.
1. charSquence should not be null otherwise it will throw NullPointerException.
2. if charSquence length is equal to zero than string buffer with no content and default capacity is return.
Commonly used methods of StringBuffer class.
Next Topic: append(String str) StringBuffer method in java.
Previous Topic: trim() String functions in java with example.