StringBuffer and StringBuilder classes in Java

As you know, String objects are immutable. Every time you create a String object, you can not change it at all. So if you create 1 string object and appended something into it, a new String object is created altogether. This wastes the memory.

That’s when StringBuffer and StringBuilder comes into picture. Objects of StringBuffer and StringBuilder classes are mutable. StringBuffer and StringBuilder are also better than String as compared to performance.

Difference between StringBuffer and StringBuilder

So both StringBuffer and StringBuilder are mutable. Which one should you use? Difference between StringBuffer and StringBuilder is that StringBuffer is synchronized while StringBuilder is not. So when you want thread-safety, you should go ahead with StrignBuffer otherwise you should go ahead with StringBuilder.

Below example illustrates how to use StringBuilder and StringBuffer in Java.

package strings;

/**
 * Created by Sagar on 20-04-2016.
 */
public class StringBuilderBuffer {

    public static void main(String [] args){

        //StringBuffer should be used when you want thread safety
        StringBuffer stringBuffer = new StringBuffer("softpost");
        stringBuffer.append(".org");
        System.out.println("Using StringBuffer -> " + stringBuffer);

        //StringBuilder should be used when you are using single thread
        StringBuilder stringBuilder = new StringBuilder("Sagar");
        stringBuilder.append("Salunke");
        System.out.println("Using StringBuilder -> " +stringBuilder);
    }
}

Here is the output of above code.

Using StringBuffer -> softpost.org
Using StringBuilder -> SagarSalunke

You may also like...