String, StringBuffer, StringBuilder

Asad Mukhtar
4 min readJul 11, 2021

--

Most of the time interviewer ask this question for a mid to senior-level android developer, few months ago same question asked by someone to me, at that time I just think like why I didn`t do any R&D on this, In this blog, I will explain String, StringBuffer, StringBuilder classes and also explain their difference and where to use them and also comparison b/w StringBuffer and StringBuilder as performance-wise and also explain few questions that interviewer ask about these classes.

An object of the String class basically represents a sequence of characters. We can use a string literal or a new Keyword to create a String object.

1. Strings are mutable or immutable in java?

String is immutable in java, immutable means that not changeable. It is represented in the UTF-16 format.

2. What is the difference b/w create a String object using String literal or using a new keyword? OR Where are the string objects saved in memory when creating objects using String literal and using New Keyword?

When an object is created using String literal it is saved in the JVM String pool (String Pool is a storage area in Java heap.), when you create a new string, it first looks in the pool with the same value if it exists then without allocating new memory for a new object it just saves the reference of another object.

When an object is created using a new keyword then it is saved in Heap memory.

Since Strings are immutable, when any operation(substring, concat, etc.) performed on String it just simply create a new one by discarding the older one, so either it’s bad for bigger projects or not?

Well, these are heavy operations and take a lot of memory, to avoid garbage in the heap, Java came up with StringBuffer and StringBuilder.

StringBuffer and StringBuilder:

Before the 1.5 version of java, java have only one class (StringBuffer) for performing operations on String, it has one disadvantage, that is all its methods are synchronized. It provides thread safety and at taking performance cost. As we mostly don`t use Strings in multithreading so java introduced StringBuilder in 1.5 that are similar to StringBuffer except for thread safety and synchronization. Few methods like trim, length are not implemented in the StringBuilder class because that all these methods are a part of the String class. Both classes are mutable.

String vs StringBuffer vs StringBuilder :

Comparison b/w these class are based on

1 . Mutability :

“Strings are immutable, and StringBuilder and StringBuffer are mutable. When you use String class, it cannot be changed whereas it changes if you use StringBuilder and StringBuffer class.”

public class MutabilityTest {public static void concatString(String hello) {
hello += "World";
}
public static void concatUsingStringBuffer(StringBuffer helloBuffer) {
helloBuffer.append("World");
}
public static void concatUsingStringBuilder(StringBuilder helloBuilder) {
helloBuilder.append("World");
}
public static void main(String[] args) {
String hello = "Hello !";
concatString(hello);
System.out.println("The final String is - " + hello);
StringBuffer helloBuffer = new StringBuffer("Hello!");
concatUsingStringBuffer(helloBuffer);
System.out.println("The final String is - " + helloBuffer);
StringBuilder helloBuilder = new StringBuilder("Hello!");
concatUsingStringBuilder(helloBuilder);
System.out.println("The final String is -" + helloBuilder);
}
}
The output of the above Program.

2. Performance :

Below table explains all the differences b/w the String, StringBuffer, and StringBuilder classes.

import java.util.GregorianCalendar;public class PerformanceTest {    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 < 10000; 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));
}
}

Test results are measured after running the above code more than 5 times.

StringBuffer Performance for above code
StringBuilder Performance for above code

Thanks for reading, clap if you like and recommend it to others,

“If you have knowledge, let others light their candles in it. …”

You can connect with me on Github Linkedin, Twitter :)

--

--