Thursday, 14 July 2016

String vs StringBuilder vs StringBuffer in Java

Consider below code with three concatenation functions with three different types of parameters, String, StringBuffer and StringBuilder.


// Java program to demonstrate difference between String,
// StringBuilder and StringBuffer
class Sudhakar
{
    // Concatenates to String
    public static void concat1(String s1)
    {
        s1 = s1 + "Sudhakar";
    }
 
    // Concatenates to StringBuilder
    public static void concat2(StringBuilder s2)
    {
        s2.append("Pandey");
    }
 
    // Concatenates to StringBuffer
    public static void concat3(StringBuffer s3)
    {
        s3.append("Pandey");
    }
 
    public static void main(String[] args)
    {
        String s1 = "Sudhakar";
        concat1(s1);  // s1 is not changed
        System.out.println("String: " + s1);
 
        StringBuilder s2 = new StringBuilder("Sudhakar");
        concat2(s2); // s2 is changed
        System.out.println("StringBuilder: " + s2);
 
        StringBuffer s3 = new StringBuffer("Sudhakar");
        concat3(s3); // s3 is changed
        System.out.println("StringBuffer: " + s3);
    }
}
Output:
String: Sudhakar
StringBuilder: SudhakarPandey
StringBuffer: SudhakarPandey
Explanation:
1. Concat1 : In this method, we pass a string “Sudhakar” and perform “s1 = s1 + ”Pandey”. The string passed from main() is not changed, this is due to the fact that String is immutable. Altering the value of string creates another object and s1 in concat1() stores reference of new string. References s1 in main() and cocat1() refer to different strings.
2. Concat2 : In this method, we pass a string “Sudhakar” and perform “s2.append(“Pandey”)” which changes the actual value of the string (in main) to “SudhakarPandey”. This is due to the simple fact that StringBuilder is mutable and hence changes its value.
2. Concat3 : StringBuffer is similar to StringBuilder except one difference that StringBuffer is thread safe, i.e., multiple threads can use it without any issue. The thread safety brings a penalty of performance.
Conclusion:
  • Objects of String are immutable, and objects of StringBuffer and StringBuilder are mutable.
  • StringBuffer and StringBuilder are similar, but StringBuilder is faster and preferred over StringBuffer for single threaded program. If thread safety is needed, then StringBuffer is used.

1 comment: