Monday, August 26, 2019

StringBuffer VS StringBuilder in Java

1. Overview


In this tutorial, We'll be learning differences between the StringBuffer and StringBuilder in java. First, let us take a brief introduction to both and see the differences.

StringBuffer is introduced in java api first and then

2. StringBuffer


This is a thread-safe, mutable sequence of characters. A string buffer is just like a String, but it can be modified using its methods such as insert() or append() methods.

This class is a thread-safe and it can be shared among multiple threads.


StringBuffer Example:

StringBuffer example program on using append(), insert(), delete() and length() methods.

package com.java.w3schools.blog.stringbuffer;

/**
 * 
 * StringBuffer Examples in java
 * 
 * @author Venkatesh
 *
 */
public class StringBufferExample {

 public static void main(String[] args) {

  StringBuffer buffer = new StringBuffer("Hello ");
  System.out.println("Buffer contents after creation: " + buffer);
  buffer.append(", Welcome to Java8Example blog");

  System.out.println("Buffer contents after append : " + buffer);
  System.out.println("Buffer length : " + buffer.length());

  buffer.insert(5, " Saying Hai ");
  System.out.println("Buffer contents after insertion : " + buffer);

  buffer.delete(5, 14);
  System.out.println("Buffer contents after deletion : " + buffer);
 }
}

Output:

Buffer contents after creation: Hello 
Buffer contents after append : Hello , Welcome to Java8Example blog
Buffer length : 36
Buffer contents after insertion : Hello Saying Hai  , Welcome to Java8Example blog
Buffer contents after deletion : Helloai  , Welcome to Java8Example blog

3. StringBuilder


This is also a mutable object but can not be used in Synchronization. Hence, This is not thread-safe.

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)

StringBuilder Example:

package com.java.w3schools.blog.stringbuilder;

/**
 * StringBuilder Example
 * 
 * @author Venkatesh
 *
 */
public class StringBuilderExample {

 public static void main(String[] args) {

  StringBuilder builder = new StringBuilder("Hello ");
  System.out.println("Builder contents after creation: " + builder);
  builder.append(", Welcome to Java8Example blog");

  System.out.println("Builder contents after append : " + builder);
  System.out.println("Builder length : " + builder.length());

  builder.insert(5, " Saying Hai ");
  System.out.println("Builder contents after insertion : " + builder);

  builder.delete(5, 14);
  System.out.println("Builder contents after deletion : " + builder);

 }

}

Output:

Builder contents after creation: Hello 
Builder contents after append : Hello , Welcome to Java8Example blog
Builder length : 36
Builder contents after insertion : Hello Saying Hai  , Welcome to Java8Example blog
Builder contents after deletion : Helloai  , Welcome to Java8Example blog

4. StringBuffer VS StringBuilder


We'll be listing the differences between StringBuffer and StringBuilder.

4.1 Thread-Safe


Both classes are mutable but StringBuffer is synchronized and StringBuilder is not synchronized. StringBuilder can not be used in multithread environments. If we know that the buffer sharing among the multiple threads will not cause any problems then we should go for StringBuilder.
We must go for StringBuffer if the data is shared by multiple threads.

4.2 Performance:


All StringBuffer methods are synchronized. So, if one thread is accessing any StringBuffer method than remaining threads have to wait until the lock is released. So, Performance will be reduced when we go with StringBuffer.

See below its internal implementation code.

    @Override
    @HotSpotIntrinsicCandidate
    public synchronized StringBuffer append(String str) {
        toStringCache = null;
        super.append(str);
        return this;
    }

    public synchronized StringBuffer append(StringBuffer sb) {
        toStringCache = null;
        super.append(sb);
        return this;
    }

    /**
     * @since 1.8
     */
    @Override
    synchronized StringBuffer append(AbstractStringBuilder asb) {
        toStringCache = null;
        super.append(asb);
        return this;
    }

  
    @Override
    public synchronized StringBuffer append(CharSequence s) {
        toStringCache = null;
        super.append(s);
        return this;
    }

    /**
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @since      1.5
     */
    @Override
    public synchronized StringBuffer append(CharSequence s, int start, int end)
    {
        toStringCache = null;
        super.append(s, start, end);
        return this;
    }

    @Override
    public synchronized StringBuffer append(char[] str) {
        toStringCache = null;
        super.append(str);
        return this;
    }

    /**
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    @Override
    public synchronized StringBuffer append(char[] str, int offset, int len) {
        toStringCache = null;
        super.append(str, offset, len);
        return this;
    }

    @Override
    public synchronized StringBuffer append(boolean b) {
        toStringCache = null;
        super.append(b);
        return this;
    }

    @Override
    @HotSpotIntrinsicCandidate
    public synchronized StringBuffer append(char c) {
        toStringCache = null;
        super.append(c);
        return this;
    }

    @Override
    @HotSpotIntrinsicCandidate
    public synchronized StringBuffer append(int i) {


Whereas all StringBuilder methods are not synchronized. So, no lock is required to access the methods. Hence, Performance will be improved when using StringBuilder.

4.3 '+' operand


Internally both are implemented using '+' operator for appending the contents.

4.4 Equals() & hashcode()


Be default, equals() and hashcode() methods are not overridden in these classes. These two methods are inherited from the Object class. So, Adding StringBuffer and StringBuilder objects into HashMap, Hashtable, and HashMap. So it is good, not to add these objects into as key's in these Map and Set.

5. Conclusion


In this article, We've seen what are the differences between StringBuilder and StringBuffer.

GitHub StringBuffer StringBuilder

StringBuffer API
StringBuilder API
Differences StackOverflow





No comments:

Post a Comment