What is the difference between String and StringBuilder in Java?
Introduction
In this shot, we will discuss the difference between String and StringBuilder in Java.
Before moving ahead, let’s look at the table of differences between String and StringBuilder.
String vs. StringBuilder
Parameter | String | StringBuilder |
Storage | String pool | Heap memory |
Mutability | Immutable | Mutable |
Performance | Slower than StringBuilder | Faster than String |
Usage in threaded environment | Not used in a threaded environment | Used in a single threaded environment |
Syntax | String variable=”String”; String variable= new String(“String”); | StringBuilder variable= new StringBuilder(“String”); |
Solution approach
-
We can approach comparing
StringandStringBuilderby creating an instance of theStringandStringBuilderclasses. -
We will perform concatenation of
Stringinstances with the+=operator and concatenation ofStringBuilderinstances with the.append()method.
append()is used to add the specified string with the string passed as an argument.
This is how we will compare the performance of String and StringBuilder.
Code
Let’s look at the code snippet below.
class Main {public static void main(String[] args) {String s = new String("This ");s+="is ";s+="String object";System.out.println(s);StringBuilder sb = new StringBuilder("This ");sb.append("is ");sb.append("StringBuilder object");System.out.println(sb);}}
Explanation
-
In line 1, we create a
Mainclass with themain()function. -
In line 3, we initialize the
Stringclass instance and concatenate it with the other strings in lines 5 and 6. -
Each time the code performs a string operation (
+=), a new string is created in the string pool. -
In line 8, we display the concatenated string.
-
In line 10, we initialize an instance of the
StringBuilderclass. -
The
StringBuilderobject will alter 2 times in lines 12 and 13. Each time the code attempts aStringBuilderoperation without creating a new object, i.e., using theStringBuilderclass can boost performance when concatenating many strings together in a loop. -
In line 15, we display the concatenated string.
In this way, we analyzed the difference between String and StringBuilder in Java.