Difference between String, StringBuffer and StringBuilder?
Difference between String, StringBuffer and StringBuilder?
String is immutable in Java. So it’s suitable to use in a multi-threaded environment. We can share it across functions because there is no concern of data inconsistency.
String overrides equals() and hashCode() methods. Two Strings are equal only if they have the same character sequence. The equals() method is case sensitive. If you are looking for case insensitive checks, you should use equalsIgnoreCase() method.
Problem with String
One of its biggest strength Immutability is also the biggest problem of Java String if not used correctly. Many times we create a String and then perform a lot of operations on them e.g. converting a string into uppercase, lowercase , getting substring out of it , concatenating with other string etc. Since String is an immutable class every time a new String is created and the older one is discarded which creates lots of temporary garbage in the heap.
StringBuffer
The main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java.
StringBuffer str=new StringBuffer();
str.append("hello");
it has one disadvantage that all of its public methods are synchronized. StringBuffer provides Thread safety but at a performance cost.
StringBuilder
If you are in a single-threaded environment or don’t care about thread safety, you should use StringBuilder. Otherwise, use StringBuffer for thread-safe operations.
StringBuilder str=new StringBuilder();
str.append("hello");
No comments: