Differences between String and StringBuffer


String is an immutable class and its object can’t be modified after it is created but definitely reference other objects. They are very useful in multithreading environment because multiple threads can’t change the state of the object so immutable objects are thread safe.

String buffer is mutable classes which can be used to do operation on string object such as reverse of string, concating string and etc. We can modify string without creating new object of the string. String buffer is also thread safe.

Also, string concat + operator internally uses StringBuffer or StringBuilder class. Below are the differences.

Sr. No.KeyStringStringBuffer
1
Basic
String is an immutable class and its object can’t be modified after it is created
String buffer is mutable classes which can be used to do operation on string object
2
Methods
Methods are not synchronized
All methods are synchronized in this class.
3
Performance
It is fast
Multiple thread can’t access at the same time therefore it is slow
4.
Memory Area
I f a String is created using constructor or method then those strings will be stored in Heap Memory  as well as SringConstantPool
Heap Space

Example of String

public class Main {
   public static void main(String args[]) {
      String s1 = "Hello Tutorials Point";
      String upperCase = s1.toUpperCase();
      System.out.println(upperCase);
   }
}

Example of StringBuffer

public class StringBufferExample{
   public static void main(String[] args){
      StringBuffer buffer=new StringBuffer("Hi");
      buffer.append("Java 8");
      System.out.println("StringBufferExample" +buffer);
   }
}

Updated on: 09-Sep-2020

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements