Difference between String and StringBuffer in Java

Difference between String and StringBuffer or String vs StringBuffer is a very commonly asked java interview question.

Both String and StringBuffer classes are used to store and manage sequence of characters but still there are some differences between them that I have explained in this tutorial.

Difference between String and StringBuffer in Java
Image Source

Difference between String and StringBuffer in Java

Mutability

String class is immutable. It means once an object is assigned a value it can’t be changed.

Example:

In above case total two objects are created. First object is created when we assign “I love” to str. When we concatenated value of str with “Java”, second object is created.

 

StringBuffer is mutable. It means we can change the value assigned to an object.

Example:

In above case only one object is created.

 

HashCode Test

Let’s make one program to prove that String is immutable and StringBuffer is mutable.

 

Output

String
Before Append: 2121855241
After Append: -952474933

StringBuffer
Before Append: 1704856573
After Append: 1704856573

 

In above example see that in case of String the hashcode of object before and after append is different. This shows String class object is immutable. While in case of StringBuffer the hashcode of object before and after append is same. This shows StrinBuffer class object is mutable.

 

Performance

String performance is low and consumes more memory than StringBuffer. In below example I am appending “Java” 1000 times to String and StrinBuffer object value. You can see the time taken to append in String is more than StringBuffer.

 

Performance Test

 

Output

Time taken for concatenation in String = 16ms
Time taken for concatenation in StringBuffer = 0ms

 

Comment below if you found anything incorrect or missing in above tutorial for String vs StringBuffer in Java.

Leave a Comment

Your email address will not be published. Required fields are marked *