String vs StringBuilder

In this section, we will discuss the comparison between Java String and StringBuilder class.

String

In Java, a string is treated as an object that represents a sequence of characters. The String class is present in java.lang package. In Java, a String object is always immutable.

StringBuilder

The StringBuilder class is used to create mutable strings. The StringBuilder is same as the StringBuffer class. The difference is StringBuilder class is not synchronized whereas, the StringBuffer class is synchronized.

The following table highlights the key points by comparing the String class with the StringBuilder classin Java.

StringStringBuilder
String is an immutable class.StringBuilder is a mutable class.
Manipulation of string is slow in the String class.Concatenation of string is quick in StringBuilder class as compared to the StringBuffer class.
Comparison of two strings can be made using the equals() method.Similar to StringBuffer, the StringBuilder class does not override the equals() method of the Object class. Hence, a comparison of two strings using the equals() method can not be made.

Performance Difference Between String and StringBuffer


The following comparison is based on the basis of the concatenation of strings for the String class and the StringBuilder class.

FileName: PerformanceTestExample.java

Output:


Explanation: Similar to StringBuffer, the StringBuilder class also takes less time as compared to the String class. The reason behind this is the time for doing the appending work is less, as the StringBuilder class is also mutable, whereas, for the String class, the time consumption is more as the String class is immutable. The immutable property of the String class leads to the creation of a new string whenever the string is manipulated. The creation of the new string, upon manipulation, is absent in the StringBuilder class.

Hash Code Test for String and StringBuilder

In the previous example, we have learned that whenever a string is manipulated, a new string is created for the String class. However, the same is not true for the StringBuilder class. Let’s confirm it with the help of an example.

FileName: HashCodeTestExample.java

Output:

Explanation: It is evident by looking at the output that, for the StringBuilder class, the hash code remains the same even after the manipulation (append work) of the string. Because of the immutability feature of the String class, the hash code changes every time when the manipulation of string is done.

Pin It on Pinterest

Share This