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

JavaObject Oriented ProgrammingProgramming

  • 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.

Example

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

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.
Output

Java Tutorials Point
raja
Published on 28-May-2019 14:31:13
Advertisements