String vs StringBuffer vs StringBuilder

Filed Under: Interview Questions

Today we will look into the difference between String vs StringBuffer vs StringBuilder. StringBuffer vs StringBuilder is a popular java interview question.

String vs StringBuffer vs StringBuilder

string vs stringbuffer vs stringbuilder
String is one of the most widely used class in java programming and one of the most important topic in core java interview. If you are writing a program which prints something on console, we use String.

This tutorial is aimed to focus on major features of String class and then we will compare String vs StringBuffer vs StringBuilder.

String in Java

  1. String class represents character strings, we can instantiate String by two ways.
    String str = "abc"; or String str = new String ("abc");
  2. String is immutable in Java, so it’s easy to share it across different threads or functions.
  3. When we create a String using double quotes, it first looks for the String with the same value in the JVM string pool, if found it returns the reference else it creates the String object and then places it in the String pool. This way JVM saves a lot of space by using the same String in different threads. But if a new operator is used, it explicitly creates a new String in the heap memory.
  4. + operator is overloaded for String and used to concatenate two Strings. Although internally it uses StringBuffer to perform this action.
  5. String overrides equals() and hashCode() methods, two Strings are equal only if they have the same characters in the same order. Note that equals() method is case sensitive, so if you are not looking for case sensitive checks, you should use equalsIgnoreCase() method.
  6. A String represents a string in the UTF-16 format
  7. String is a final class with all the fields as final except “private int hash”. This field contains the hashCode() function value and created only when the hashCode() method is called and then cached in this field. Furthermore, the hash is generated using final fields of String class with some calculations, so every time hashCode() method is called, it will result in the same output. For the caller, it’s 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 class that should be used for String manipulation.

StringBuffer and StringBuilder are mutable objects in java and provide append(), insert(), delete() and substring() methods for String manipulation.

StringBuffer vs StringBuilder

StringBuffer was the only choice for String manipulation till Java 1.4 but it has one disadvantage that all of its public methods are synchronized. StringBuffer provides Thread safety but on 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 that is similar to StringBuffer except thread safety and synchronization.

So if you are in a single threaded environment or don’t care about thread safety, you should use StringBuilder else use StringBuffer. See this post for performance benchmarking between StringBuffer and StringBuilder.

String vs StringBuffer vs StringBuilder

  1. String is immutable whereas StringBuffer and StringBuider are mutable classes.
  2. StringBuffer is thread safe and synchronized whereas StringBuilder is not, thats why StringBuilder is more faster than StringBuffer.
  3. String concat + operator internally uses StringBuffer or StringBuilder class.
  4. For String manipulations in non-multi threaded environment, we should use StringBuilder else use StringBuffer class.

That’s all for a quick roundup of difference between String vs StringBuffer vs StringBuilder. In most of the scenarios for string manipulation, StringBuilder is better suited than StringBuffer.

References:

Comments

  1. Krishna Revuru says:

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

  2. emilio says:

    + 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.

    Example here

    1. Bunthai says:

      This is also my question!!

  3. subrat panda says:

    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.

    1. Pankaj says:

      String is immutable because once we instantiate it, there is no way to change it’s value whereas StringBuffer and StringBuilder is mutable because they provide append() method to update its content.

      If your custom immutable class has a mutable field, you should return the defensive copy of that variable in get() method. For example, let’s say you have a List<String> variable in your class, so your get method should be something like

      public List<String> get(){
      return (List<String>) myList.clone();
      }
      

      So now even if you update the contents of the returned List, it won’t update the content of list in our immutable object.

      Read this post for further details: https://www.journaldev.com/129/how-to-write-an-immutable-class

  4. Mikhail Seleznev says:

    “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.

    1. Pankaj says:

      Good observation, updated the post.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages