This post will discuss the difference between string and StringBuilder (or StringBuffer) in Java.

1. Mutability

A String is immutable in Java, while a StringBuilder is mutable in Java. An immutable object is an object whose content cannot be changed after it is created.

When we try to concatenate two Java strings, a new String object is created in the string pool. This can be demonstrated by comparing HashCode for String object after every concat operation.

Download  Run Code

Output:

2081
64578

 
As evident from the above code, a new hashcode is generated after concatenation, proving that a new String object is created with updated values and the old object was dereferenced.

2. Equality

We can use the equals() method for comparing two strings in Java since the String class overrides the equals() method of the Object class, while StringBuilder doesn’t override the equals() method of the Object class and hence equals() method cannot be used to compare two StringBuilder objects.

Download  Run Code

Output:

true
false

3. Comparable

The String class implements the Comparable interface, while StringBuilder doesn’t. To illustrate, consider the following code, which throws ClassCastException since StringBuilder doesn’t provide any mechanism for string comparison.

Download  Run Code

Output:

java.lang.StringBuilder cannot be cast to java.lang.Comparable

4. Constructor

We can create a String object without using a new operator, which is not possible with a StringBuilder.

is equivalent to:

5. Performance

StringBuilder is speedy and consumes less memory than a string while performing concatenations. This is because string is immutable in Java, and concatenation of two string objects involves creating a new object.

To illustrate, consider the following code, which logs the time taken by both string and StringBuilder objects on multiple concatenations.

Download  Run Code

Output (will vary):

The time taken by string concatenation: 504774386ns
The time taken by StringBuilder concatenation: 1081315ns

6. Length

Since String is immutable, its length is fixed. But StringBuilder has the setLength() method, which can change the StringBuilder object to the specified length.

When to use string and StringBuilder?

A String can be used when immutability is required, or concatenation operation is not required. A StringBuilder can be used when a mutable string is needed without the performance overhead of constructing lots of strings along the way.

That’s all about the differences between String and StringBuilder in Java.