In Java, String is an immutable object that is used to store a sequence of characters, whereas StringBuffer is a mutable object that allows modifications to the same character sequence. In this chapter, we will understand the difference between String and StringBuffer, along with their definitions and examples.
String represents an immutable sequence of characters that means its value cannot be changed once it is created.
The following example demonstrates String immutability:
Java
Compile and RunOutput:
Hello World
The original string "Hello" is not modified. A new String object is created when concat() is called, which shows that String objects are immutable.
StringBuffer represents a mutable sequence of characters that allows changes such as appending or modifying content without creating a new object.
The following example demonstrates StringBuffer mutability:
Java
Compile and RunOutput:
Hello World
Here, the original object is modified using append(), which proves that StringBuffer is mutable.
There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given below:
| String | StringBuffer |
|---|---|
| The String class is immutable. | The StringBuffer class is mutable. |
| String is slow and consumes more memory when we concatenate too many strings because every time it creates new instance. | StringBuffer is fast and consumes less memory when we concatenate t strings. |
| String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. | StringBuffer class doesn't override the equals() method of Object class. |
| String class is slower while performing concatenation operation. | StringBuffer class is faster while performing concatenation operation. |
| String class uses String constant pool. | StringBuffer uses Heap memory |

This example shows that String is slower in repeated concatenation because it creates new objects each time, while StringBuffer is faster since it modifies the same object, making it more efficient for frequent string changes.
The following example demonstrate how to test the performance of string and stringbuffer.
Java
Compile and RunOutput:
Time taken by Concating with String: 578ms Time taken by Concating with StringBuffer: 0ms
The above code, calculates the time required for concatenating a string using the String class and StringBuffer class.
As shown in the program below, a String returns a new hashcode after concatenation because it creates a new object, whereas StringBuffer retains the same hashcode since the same object is modified.
The following example demonstrate how to test the hashcode of string and stringbuffer.
Java
Compile and RunOutput:
Hashcode test of String: 3254818 229541438 Hashcode test of StringBuffer: 118352462 118352462
Quick summary of difference between string and StringBuffer is:
We request you to subscribe our newsletter for upcoming updates.