Difference between StringBuilder and StringBuffer in Java

StringBuilder vs StringBuffer in Java

In this article we are going to discuss difference between StringBuilder and StringBuffer class in java. This is one of frequently asked question in core java interview question. In very short StringBuffer is thread-safe means all methods in StringBuffer class are synchronized but StringBuilder is not thread-safe and both classes are mutable unlike String. StringBuffer is available from JDK 1.0 but StringBuilder is available from JDK 1.5. Actually StringBuilder is the copy of StringBuffer without thread safety. In java there are three classes related to string manipulation String, StringBuffer and StringBuilder in the java.lang package.

Out of these three classes String is immutable by nature. while StringBuilder and StringBuffer are mutable version of String. String immutability nature because of many reasons related like Security, String Pool, and Performance.

Difference between StringBuffer and StringBuilder in Java

StringBuffer and StringBuilder classes are mutable version of String class. They all have common methods for string manipulation in spite of this they have difference in uses in java application. Before going to differences let’s discuss some words about both classes from java documents.

StringBuffer class

A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

public synchronized int length() {
 return count;
    }

    public synchronized int capacity() {
 return value.length;
    }


    public synchronized void ensureCapacity(int minimumCapacity) {
 if (minimumCapacity > value.length) {
     expandCapacity(minimumCapacity);
 }
    }

    /**
     * @since      1.5
     */
    public synchronized void trimToSize() {
        super.trimToSize();
    }

    /**
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @see        #length()
     */
    public synchronized void setLength(int newLength) {
 super.setLength(newLength);
    }

    /**
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @see        #length()
     */
    public synchronized char charAt(int index) {
 if ((index < 0) || (index >= count))
     throw new StringIndexOutOfBoundsException(index);
 return value[index];
    }

//Many more methods.....

StringBuilder class

A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

public StringBuilder append(Object obj) {
 return append(String.valueOf(obj));
    }

    public StringBuilder append(String str) {
 super.append(str);
        return this;
    }

    // Appends the specified string builder to this sequence.
    private StringBuilder append(StringBuilder sb) {
 if (sb == null)
            return append("null");
 int len = sb.length();
 int newcount = count + len;
 if (newcount > value.length)
     expandCapacity(newcount);
 sb.getChars(0, len, value, count);
 count = newcount;
        return this;
    }

       /**
     * @throws StringIndexOutOfBoundsException {@inheritDoc}
     */
    public StringBuilder delete(int start, int end) {
 super.delete(start, end);
        return this;
    }

    /**
     * @throws StringIndexOutOfBoundsException {@inheritDoc}
     */
    public StringBuilder deleteCharAt(int index) {
        super.deleteCharAt(index);
        return this;
    }

    /**
     * @throws StringIndexOutOfBoundsException {@inheritDoc}
     */
    public StringBuilder replace(int start, int end, String str) {
        super.replace(start, end, str);
        return this;
    }

    /**
     * @throws StringIndexOutOfBoundsException {@inheritDoc}
     */
    public StringBuilder insert(int index, char str[], int offset,
                                int len) 
    {
        super.insert(index, str, offset, len);
 return this;
    }

//Many more methods.....

StringBuider vs StringBuffer

There are following are main difference between StringBuffer and StringBuilder in Java

Synchronization
All Methods in StringBuffer class are synchronized but StringBuilder is non synchronized. In short StringBuilder unsynchronized version of StringBuffer class. You can not share Instances of StringBuilder class between multiple threads. If such synchronization is required then it is better to use StringBuffer class.

Performance
Due thread-safe nature of StringBuffer make it slower than StringBuilder because of StringBuffer has overhead of acquiring and releasing locks associated with synchronized methods.

From which java version
StringBuffer is available from JDK 1.0 but StringBuilder is available from JDK 1.5.

Which one to use and when
StringBuffer and StringBuilder are almost same, both classes have same methods but StringBuffer has synchronized methods due to thread-safety. So that means if thread-safety is matter and performance is not matter for any operation then we should use StringBuffer instead of StringBuilder. There some areas in the application where performance is matter without thread safety then StringBuilder could be used. In short if you think that the operation should be thread-safe then use StringBuffer, in all other cases StringBuilder is a better choice as it offers you the same functionality with better performance.

Interested Point about String Concatenation
Suppose you want concatenate two or more strings using + operator, Java internally convert that operator call to corresponding StringBuilder append() method. For example there are three string literals “Dinesh”, ” on ” , “Java” if want to add these three literal to make final string “Dinesh on Java” then we can concatenate these as “Dinesh” + ” on ” + “Java”, that will be converted to new StringBuilder().append(“Dinesh”).append(” on “).append(“Java”). Only problem is that it initialize StringBuilder with default capacity, which means expensive array copy operation, when StringBuilder get resized. So be careful whenever you want to concatenation of strings, in this case always use StringBuilder or StringBuffer.

Summary

In this article we have seen the basic features and some differences of StringBuffer and StringBuilder. StringBuffer and String class both are from Java first version but StringBuilder added from Java 5. StringBuffer and StringBuilder both classes are mutable unlike String is immutable. StringBuffer is thread-safe in nature i.e. all methods of this class are synchronized. But StringBuilder is simply unsynchronized copy of StringBuffer class.

Previous
Next