Why should we use a StringBuffer instead of a String in Java?n

  • A StringBuffer is a thread-safe, mutable sequence of characters.
  • Unlike a String class (immutable), the StringBuffer class is mutable. That is, we can change the contents of a StringBuffer object.
  • When we modify a string of StringBuffer class, we are not creating a new String object, but rather operating directly on the original string itself.
  • For this reason, the StringBuffer class offers a different set of methods than the String class, all of which operate directly on the buffer that contains the string.
  •  A StringBuffer can be defined simply by the use of the new operator and bypassing the string value inside a     StringBuffer constructor.


class StringBufferDemo{
   public static void main(String arg[]){
      StringBuffer sb = new StringBuffer();
      sb.append("Java Tutorials Point");

In the above program, we initially created an instance of a StringBuffer class and appended "Java Tutorials Point" to the StringBuffer class using append() method.

Java Tutorials Point