StringBuffer in Java

  • StringBuffer is a synchronized and allows us to mutate the string.
  • StringBuffer has many utility methods to manipulate the string.
  • This is more useful when using in a multithreaded environment. 
  • StringBuffer class represents a String that can be dynamically modified.
  • It contain sequences of 16-bit Unicode characters.Uses a buffer that is much larger than any one string; actual size of the buffer is the capacity.Provides methods that can change individual characters within a string
StringBuffer() - create an empty buffer
StringBuffer(int length) - create an empty buffer with a initial capacity
StringBuffer (String str)

Modification Operations: append, insert, reverse, setCharAt and setLength

  • Use toString() to returns the encapsulated string in StringBuffer object.
  • The concat() method of the String class and the append() method of the StringBuffer class glue two strings together. An easier way to concatenate strings is to use Java’s overloaded + operator.
Example: a + b + c

The Java compiler treats the code above as if it were the following:
New StringBuffer().append(a).append(b).append(c).toString();


public class mybuffers{
 public static void main(String args[]){
  StringBuffer buffer =  new StringBuffer(“Hi”);