Difference between StringBuffer and StringBuilder

There are many differences between StringBuffer and StringBuilder. A list of differences between StringBuffer and StringBuilder are given below:
No.StringBufferStringBuilder
1)StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2)StringBuffer is less efficient than StringBuilder.StringBuilder is more efficient than StringBuffer.

StringBuffer

Example:

public class BufferExample{  
public static void main(String[] args){  
     StringBuffer buffer=new StringBuffer("hello");  
      buffer.append("java");  
    System.out.println(buffer);  
    }  
   } 

Output:

hellojava

StringBuilder

Example:

public class BuilderExample{  
public static void main(String[] args){  
        StringBuilder builder=new StringBuilder("hello");  
        builder.append("java");  
        System.out.println(builder);  
    }  
}  

Output:

hellojava

Performance Test of StringBuffer and StringBuilder

see the code to check the performance of StringBuffer and StringBuilder classes.

Example:

public class ConcatExample{  
    public static void main(String[] args){  
        long startTime = System.currentTimeMillis();  
        StringBuffer sb = new StringBuffer("Java");  
        for (int i=0; i<10000; i++){  
            sb.append("Catchme");  
        }  
        System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");  
        startTime = System.currentTimeMillis();  
        StringBuilder sb2 = new StringBuilder("Java");  
        for (int i=0; i<10000; i++){  
            sb2.append("Catchme");  
        }  
        System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  
    }  
}

Output:

Time taken by StringBuffer: 13ms
Time taken by StringBuilder: 3ms

How to create Immutable class?

There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable. We can also create immutable class by creating final class that have final data members as the example given:

Example:

public final class Employee{  
final String idNumber;  
public Employee(String idNumber){  
this.idNumber=idNumber;  
}  
public String getidNumber(){  
return idNumber;  
}  
}   
The above class is immutable because:
  • The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
  • The class is final so we cannot create the subclass.
  • There is no setter methods i.e. we have no option to change the value of the instance variable.
  • These points makes this class as immutable.