Difference Between String StringBuffer and StringBuilder

In this tutorial, we will discuss the main difference between String, StringBuffer, and StringBuilder in Java with examples.

Java language provides three classes: String, StringBuffer, and StringBuilder to work with string that represents a sequence of characters.

The String class is used to create an immutable (i.e., unmodifiable) string. An immutable string is that string whose content cannot be changed once it is created.

StringBuffer and StringBuilder classes are used to create mutable (i.e., modifiable) string. A mutable string is that string whose content can be changed or modified.

String and StringBuffer classes were added in JDK 1.0. StringBuilder class was introduced in JDK 1.5.

It has exactly similar API as StringBuffer class, except StringBuilder is not thread safe. In other words, its methods are not synchronized.

Sun recommends to use StringBuilder instead of StringBuffer whenever possible because StringBuilder will execute faster than StringBuffer.

Let’s understand the main difference between String, StringBuffer, and StringBuilder in Java.

String vs StringBuffer vs StringBuilder in Java


Difference between String, StringBuffer and StringBuilder in java

1. Immutable and Mutable:

a) String in Java is immutable and final class. That means objects of string class cannot be changed once it created. So, whenever we change any string or perform string manipulation, it will create a new object.

Let’s understand it with the help of an example program.

Program code:

public class Test {
 public static void main(String [] args)
 {
  String str = new String("Scientech");
    str.concat("Easy"); // concat() method adds string at the end.
    System.out.println(str); // It will print "Scientech" because string is an immutable object.
 }
}
Output:
        Scientech

In the above program, the new object is not assigning with any reference variable. Therefore, it is called unreferenced object and the garbage collector will automatically remove it from the memory.


b) StringBuffer in Java is a mutable class. That means, objects of StringBuffer class can be changed. Let’s understand it with the help of an example program.

Program code:

public class Test {
 public static void main(String [] args)
 {
   StringBuffer sb = new StringBuffer("Scientech");
     sb.append(" Easy"); // This append() method will add string object "Easy" at the end of existing string.
   System.out.println(sb); // Print Scientech Easy because StringBuffer is a mutable class.
 }
}
Output:
       Scientech Easy

c) StringBuilder is a mutable class in Java. That means, objects of StringBuilder class can be modified or changed. Look at the program source code to understand it.

Program code:

public class Test {
 public static void main(String [] args)
 {
    StringBuilder sb = new StringBuilder("Scientech");
     sb.append(" Easy"); 
    System.out.println(sb);
 }
}
Output:
      Scientech Easy

2. Object creation:

a) An instance of String can be created into two ways:

  • Using string literal
  • Using new operator

Let’s take an example to understand both ways.

// By String literal.
	String str = "Java";
 // By new operator.
	String str2 = new String("Programming");

b) An instance of StringBuffer and StringBuilder can be created in only one way:

  • Using new operator

For example:

StringBuffer sb = new StringBuffer("Java Programming");
StringBuilder sbl = new StringBuilder("Java World");

3. String Constant Pool:

a) Internally, String class uses the string constant pool (SCP) for storing string objects to save the memory. Whenever we create a string literal, JVM checks string constant pool first.

If the string already exists in string constant pool, no new string object will be created in the string pool by JVM.

b) There is no concept of String constant pool in the case of StringBuffer and StringBuilder.


4. Uses:

a) String class should be used when the content is fixed and not change frequently.

b) StringBuffer class should be used when content is not fixed and often changing but also need thread safety.

c) StringBuilder class should be used when content is not fixed and often changing but also do not need thread safety.


5. Memory:

a) String consume more memory when we concat too many strings because every time it creates a new object.

b) StringBuffer and StringBuilder consume less memory when we append strings.


6. Speed:

a) String is slower than StringBuffer and StringBuilder.

b) StringBuffer is slower than StringBuilder, but it is faster than String.

c) StringBuilder is faster than string and StringBuffer.

Let’s create a program in which we will test performance of String, StringBuffer, and StringBuilder classes.

Program code:

public class PerformanceTest {
 public static void main(String [] args)
 {
  long startTime = System.currentTimeMillis();
   String str = new String("Java");
   for (int i = 0; i < 1000; i++) {  
       str.concat("Technology");  
   }  
  System.out.println("Time taken by String: " + (System.currentTimeMillis() - startTime) + "ms");
  
  startTime = System.currentTimeMillis();  
  StringBuffer sbuffer = new StringBuffer("Java");  
   for (int i = 0; i < 1000; i++) {  
         sbuffer.append("Technology");  
     }  
   System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");  
    
   startTime = System.currentTimeMillis();  
   StringBuilder sbuilder = new StringBuilder("Java");  
     for (int i = 0; i < 1000; i++) {  
         sbuilder.append("Technology");  
     }  
     System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  
 }
}
Output:
     Time taken by String: 6ms
     Time taken by StringBuffer: 5ms
     Time taken by StringBuilder: 3ms

7. Override equals() and hashCode() methods of Object class:

a) String class overrides the equals() of the Object class to compare contents of two strings as well as hashCode() method.

b) SringBuffer and StringBuilder classes do not override the equals() and hashCode() methods of Object class.

Let’s create a Java program in which we will compare two strings using equals() method. The equals() method of Object class compares the references of two objects. If two objects have the same references, then it returns true.

The equals() method of the String class is not same as the equals() method of the Object class. It is overridden, this method accepts a String value and compares it with the current object and returns true .

Whereas the equals() method of String class is not similar to the equals() method of Object class. It is overridden method of equals() method of Object class that accepts a string value and compares it with the current string object.

It returns true only if the sequence of characters in the both String objects are exactly the same. If the equals() methods returns true on comparing two string objects, their hash code values must be same.

Program code:

public class StringEqualsDemo {
 public static void main(String [] args)
 {
   String s = new String("Love Java Programming");
   String str = new String("Love Java Programming");
   boolean compare = s.equals(str);
   System.out.print(compare);
   System.out.println();
   System.out.println(s.hashCode());
   System.out.println(str.hashCode());  
 }
}
Output:
    true
   -302294359
   -302294359

As you observe in the program, sting class overrides equals() method of Object class, compares contents of strings, and returns true as both are having the same contents.


StringBuffer class does not override the equals() method of Object class. Its functionality is similar to the equals() method of the Object class. Let’s understand and see if we can compare two stringBuffer objects using equals() method.

Program code:

public class StringBufferEqualsDemo {
 public static void main(String [] args)
 {
   StringBuffer sb = new StringBuffer("Like");
   StringBuffer sb2 = new StringBuffer("Love");
   boolean compare = sb.equals(sb2);
   System.out.print(compare);
   
   System.out.println();
   System.out.println(sb.hashCode());
   System.out.println(sb2.hashCode());
 }
}
Output:
       false
       31168322
       17225372

As you can observe in this program, when we are comparing two stringBuffer objects using equal() method, it returns false even content is same. Because StringBuffer class not overriding equals() and hashcode() methods of Object class. ​


8. Thread-safe:

a) String class is not recommended to use in threaded environment.

b) StringBuffer class is recommended to use in multithreaded environment.

c) StringBuilder class is recommended to use in a single threaded environment.

What is Difference between String and StringBuffer in Java?


There are several differences between String and StringBuffer in Java. They are as follows:

1. String class is immutable, but StringBuffer class is mutable.

2. String objects can be created using string literal and new operator, but StringBuffer objects can be created only using new operator.

3. String class uses string constant pool to store string objects, but StringBuffer class does not use string constant pool.

4. Strings are of fixed length, whereas StringBuffers are of variable length.

5. String is slower than StringBuffer.

6. String consumes more memory when we will concat too many strings, but StringBuffer consumes less memory when we concat or update strings.

7. Java String class overrides the equal() method of the Object class. So, we can compare contents of two strings by using equals() method. The StringBuffer class does not override the equals() method of Object class.

8. String should be used when we do not need to change or modify the content of string. Whereas, StringBuffer should be used when we need to change or modify the content of string frequently.

9. String cannot be used in a threaded environment, but StringBuffer can be used in a multithreaded environment.

What is Difference between StringBuffer and StringBuilder in Java?


There are mainly five differences between StringBuffer and StringBuilder in Java. They are as follows:

1. Methods of StringBuffer is synchronized. That means, two threads cannot call methods of StringBuffer simultaneously. Therefore, StringBuffer is thread-safe.

But, methods of StringBuilder is not synchronized. That means, two or more threads can call methods of StringBuilder simultaneously. Therefore, StringBuilder is not thread-safe.

2. It is faster than StringBuffer.

3. It is more efficient than StringBuffer.

4. StringBuilder was added in Java 5 version, whereas StringBuffer was added in Java 1 version.

5. StringBuffer is used in a multithreaded environment, but StringBuilder is used in the single threaded environment.


In this tutorial, you learned the main difference between String, StringBuffer, and StringBuilder classes in Java with example programs. Hope that you will have understood all the informative points related to String vs StringBuffer vs StringBuilder.
Thanks for reading!!!
Next ⇒ Immutable Class in Java⇐ Prev Next ⇒