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
.
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”); |
We can approach comparing String
and StringBuilder
by creating an instance of the String
and StringBuilder
classes.
We will perform concatenation of String
instances with the +=
operator and concatenation of StringBuilder
instances 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
.
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);}}
In line 1, we create a Main
class with the main()
function.
In line 3, we initialize the String
class 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 StringBuilder
class.
The StringBuilder
object will alter 2 times in lines 12 and 13. Each time the code attempts a StringBuilder
operation without creating a new object, i.e., using the StringBuilder
class 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.