Difference between String class and StringBuffer class in Java



Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings.

Whereas, StringBuffer class is a thread-safe, mutable sequence of characters.

  • A string buffer is like a String, but can be modified.
  • It contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
  • They are safe for use by multiple threads.
  • Every string buffer has a capacity.

Example

Live Demo

public class Sample {
   public static void main(String args[]) {
      String str = new String("Hi welcome to tutorialspoint");
      System.out.println(str);
      StringBuffer sBuffer = new StringBuffer("test");
      sBuffer.append(" String Buffer");
      System.out.println(sBuffer);
   }
}

Output

Hi welcome to tutorialspoint
test String Buffer

Advertisements