Javatpoint Logo
Javatpoint Logo

Difference between String and StringBuffer

There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given below:

No.StringStringBuffer
1) The String class is immutable. The StringBuffer class is mutable.
2) 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.
3) 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.
4) String class is slower while performing concatenation operation. StringBuffer class is faster while performing concatenation operation.
5) String class uses String constant pool. StringBuffer uses Heap memory

String vs StringBuffer

Performance Test of String and StringBuffer

ConcatTest.java

Output:

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.

String and StringBuffer HashCode Test

As we can see in the program given below, String returns new hashcode while performing concatenation but the StringBuffer class returns same hashcode.

InstanceTest.java

Output:

Hashcode test of String:
3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA