In the last post we discussed the difference between StringBuffer and StringBuilder. Here we are gonna discuss the differences between
String vs StringBuffer
1) Mutability: String is immutable (Once created, cannot be modified) while StringBuffer is mutable (can be modified).
String is immutable:
String str = "Hello World"; str = "Hi World!";
By seeing this code you would say that the value of str has changed so how can it be immutable? Let me explain this:
In first statement an object is created using string literal “Hello World”, in second statement when we assigned the new string literal “Hi World!” to
str, the object itself didn’t change instead a new object got created in memory using string literal “Hi World!” and the reference to it is assigned to
str. So basically both the objects “Hello World” and “Hi World!” exists in memory having different references(locations).
StringBuffer is mutable:
Lets see StringBuffer mutability
StringBuffer sb = new StringBuffer("Hello"); sb.append(" World");
In the first statement StringBuffer object got created using string literal “Hello” and in second statement the value of the object got changed to “Hello World” from “Hello”. Unlike Strings here the object got modified instead of creating the new object.
2) Performance: While performing concatenations you should prefer
String because it is faster. The reason is: When you concatenate strings using String, you are actually creating new object every time since String is immutable.
What java documentation says about StringBuffer:
From StringBuffer javadoc:
A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
Leave a Reply