Tutorial

String vs StringBuffer vs StringBuilder

Published on August 3, 2022
Default avatar

By Pankaj

String vs StringBuffer vs StringBuilder

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

String is one of the most widely used classes in Java. StringBuffer and StringBuilder classes provide methods to manipulate strings. We will look into the difference between StringBuffer and StringBuilder. StringBuffer vs StringBuilder is a popular Java interview question.

String vs StringBuffer vs StringBuilder

The string is one of the most important topics in the core java interview. If you are writing a program that prints something on the console, you are use String. This tutorial is aimed to focus on major features of String class. Then we will compare the StringBuffer and StringBuilder classes.

String in Java

  1. String class represents character strings, we can instantiate String in two ways.

    String str = "ABC";
    // or 
    String str = new String("ABC");
    
  2. String is immutable in Java. So it’s suitable to use in a multi-threaded environment. We can share it across functions because there is no concern of data inconsistency.

  3. When we create a String using double quotes, JVM first looks for the String with the same value in the string pool. If found, it returns the reference of the string object from the pool. Otherwise, it creates the String object in the String pool and returns the reference. JVM saves a lot of memory by using the same String in different threads.

  4. If the new operator is used to create a string, it gets created in the heap memory.

  5. The + operator is overloaded for String. We can use it to concatenate two strings. Although internally it uses StringBuffer to perform this action.

  6. String overrides equals() and hashCode() methods. Two Strings are equal only if they have the same character sequence. The equals() method is case sensitive. If you are looking for case insensitive checks, you should use equalsIgnoreCase() method.

  7. The string uses UTF-16 encoding for the character stream.

  8. String is a final class. All the fields as final except “private int hash”. This field contains the hashCode() function value. The hashcode value is calculated only when the hashCode() method is called for the first time and then cached in this field. Furthermore, the hash is generated using the final fields of String class with some calculations. So every time the hashCode() method is called, it will result in the same output. For the caller, it seems like calculations are happening every time but internally it’s cached in the hash field.

String vs StringBuffer

Since String is immutable in Java, whenever we do String manipulation like concatenation, substring, etc. it generates a new String and discards the older String for garbage collection. These are heavy operations and generate a lot of garbage in heap. So Java has provided StringBuffer and StringBuilder classes that should be used for String manipulation. StringBuffer and StringBuilder are mutable objects in Java. They provide append(), insert(), delete(), and substring() methods for String manipulation.

StringBuffer vs StringBuilder

StringBuffer was the only choice for String manipulation until Java 1.4. But, it has one disadvantage that all of its public methods are synchronized. StringBuffer provides Thread safety but at a performance cost. In most of the scenarios, we don’t use String in a multithreaded environment. So Java 1.5 introduced a new class StringBuilder, which is similar to StringBuffer except for thread-safety and synchronization. StringBuffer has some extra methods such as substring, length, capacity, trimToSize, etc. However, these are not required since you have all these present in String too. That’s why these methods were never implemented in the StringBuilder class. StringBuffer was introduced in Java 1.0 whereas StringBuilder class was introduced in Java 1.5 after looking at shortcomings of StringBuffer. If you are in a single-threaded environment or don’t care about thread safety, you should use StringBuilder. Otherwise, use StringBuffer for thread-safe operations.

StringBuilder vs StringBuffer Performance

I am trying to check the effect on performance because of synchronization with a sample program that performs append() on StringBuffer and StringBuilder object for multiple times.

package com.journaldev.java;

import java.util.GregorianCalendar;

public class TestString {

	public static void main(String[] args) {
		System.gc();
		long start=new GregorianCalendar().getTimeInMillis();
		long startMemory=Runtime.getRuntime().freeMemory();
		StringBuffer sb = new StringBuffer();
		//StringBuilder sb = new StringBuilder();
		for(int i = 0; i<10000000; i++){
			sb.append(":").append(i);
		}
		long end=new GregorianCalendar().getTimeInMillis();
		long endMemory=Runtime.getRuntime().freeMemory();
		System.out.println("Time Taken:"+(end-start));
		System.out.println("Memory used:"+(startMemory-endMemory));
	}
}

I ran the same code for the StringBuffer object also to check the time and memory values. I have executed the code 5 times for each case and then calculated the average values.

Value of i StringBuffer (Time, Memory) StringBuilder (Time, Memory)
10,00,000 808, 149356704 633, 149356704
1,00,00,000 7448, 147783888 6179, 147783888

It’s clear that StringBuilder performs better than StringBuffer even in the case of a single-threaded environment. This difference in performance can be caused by synchronization in StringBuffer methods.

String vs StringBuffer vs StringBuilder

  1. String is immutable whereas StringBuffer and StringBuilder are mutable classes.
  2. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That’s why StringBuilder is faster than StringBuffer.
  3. String concatenation operator (+) internally uses StringBuffer or StringBuilder class.
  4. For String manipulations in a non-multi threaded environment, we should use StringBuilder else use StringBuffer class.

That’s all for a quick roundup of difference between String, StringBuffer, and StringBuilder. StringBuilder is better suited than StringBuffer in most of the general programming scenarios. References:

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 9, 2021

please correct me if i am wrong string in string pool is not garbage collected and string in heap are garbage collected right ?

- rizwan

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 31, 2019

    Pankaj, On the very same context, also include a note for StringJoiner.

    - Krishna Revuru

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 20, 2014

      + operator is overloaded for String and used to concatenate two Strings. Although internally it uses StringBuffer to perform this action. As I know internally it is uses StringBuilder to perform this action.

      - emilio

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        July 23, 2013

        If we look both String and StringBuilder both are final class and fields are also final, then what extra property is there in String class, that make it immutable and StringBuilder as immutable. Please provide me the solution. Q2:-When we are creating our custom immutable class, generally we are making our class as 1)final, 2)all the fields are making final and initializing them with the help of constructor 3) only providing the getter methods, no setter methods It will holds good for primitive type data Type or immutable class(StringBuffer), what if in our class there is a mutable property is there, how to achieve immutable in that case. Please provide me the answer with example. From a long time I was looking for this answer. nb:- from interet I found something like make the defense copy of that property, but I didn’t get how exactly I ll achieve that.

        - subrat panda

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          January 26, 2013

          “But if new operator is used, it explicitly creates a new String and then add it to the pool.” Operator new creates a new String but doesn’t add String to the pool. Method intern() does that.

          - Mikhail Seleznev

            Try DigitalOcean for free

            Click below to sign up and get $200 of credit to try our products over 60 days!

            Sign up

            Join the Tech Talk
            Success! Thank you! Please check your email for further details.

            Please complete your information!

            Get our biweekly newsletter

            Sign up for Infrastructure as a Newsletter.

            Hollie's Hub for Good

            Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

            Become a contributor

            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

            Welcome to the developer cloud

            DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

            Learn more
            DigitalOcean Cloud Control Panel