Ask a Question
Advertise on boostr.in
Difference between String and StringBuffer
In the last post we discussed the difference between StringBuffer and StringBuilder. Here we are gonna discuss the differences between String and StringBuffer class.
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");
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 StringBuffer over 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.
Jun 11, 2015
Java Interview Questions
to add a comment.
Your name to display (optional):
Email me at this address if my answer is selected or commented on:
Email me if my answer is selected or commented on
Privacy: Your email address will only be used for sending these notifications.
To avoid this verification in future, please