Difference between StringBuilder and StringBuffer
StringBuffer
is synchronized, StringBuilder
is not.
Difference between String , StringBuilder & StringBuffer?
I will clarify the thread-safety point. The other points are well described in older questions.
It's quite rare case when StringBuffer
suits your needs. While it's thread-safe it doesn't mean you will get what expected when using it from different threads. For example, suppose you have the following code:
StringBuffer buf = new StringBuffer();
public void appendMessage(String message) {
buf.append("INFO: ").append(message).append(System.lineSeparator());
}
If you are using it in multithread environment it will not fail, but you may end up having content like this:
INFO: INFO: thread1 message
thread2 message
That's because individual append
calls are synchronized, but the whole sequence is not.
In order to ensure that your messages are separately added, you must have an external synchronization like this:
Object lock = new Object();
StringBuilder buf = new StringBuilder();
public void appendMessage(String message) {
synchronized(lock) {
buf.append("INFO: ").append(message).append(System.lineSeparator());
}
}
Here the whole sequence of calls is synchronized, so you will have the whole message appended at once. And as you are using the external synchronization, StringBuilder
will work fine as well.
So in general StringBuffer
should not be used in the most of situations.
String, StringBuffer, and StringBuilder
Mutability Difference:
String
is immutable, if you try to alter their values, another object gets created, whereas StringBuffer
and StringBuilder
are mutable so they can change their values.
Thread-Safety Difference:
The difference between StringBuffer
and StringBuilder
is that StringBuffer
is thread-safe. So when the application needs to be run only in a single thread then it is better to use StringBuilder
. StringBuilder
is more efficient than StringBuffer
.
Situations:
- If your string is not going to change use a String class because a
String
object is immutable. - If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a
StringBuilder
is good enough. - If your string can change, and will be accessed from multiple threads, use a
StringBuffer
becauseStringBuffer
is synchronous so you have thread-safety.
Where to use StringBuffer/StringBuilder than String
Below is the main difference between these three most commonly used classes.
- String class objects are immutable whereas StringBuffer and
StringBuilder objects are mutable. - StringBuffer is synchronized while StringBuilder is not synchronized.
- Concatenation operator "+" is internal implemented using either
StringBuffer or StringBuilder.
Criteria to choose among String, StringBuffer and StringBuilder
- If the Object value is not going to change use String Class because a
String object is immutable. - If the Object value can change and will only be accessed from a
single thread, use a StringBuilder because StringBuilder is
unsynchronized. - In case the Object value can change, and will be modified by multiple
threads, use a StringBuffer because StringBuffer is synchronized.
StringBuffer vs StringBuilder Vs StringTokenizer
StringBuffer
- introduced in JDK 1.0 - is thread safe (all of its methods are synchronized
), while StringBuilder
- since JDK 1.5 - is not. Thus it is recommended to use the latter under normal circumstances.
StringTokenizer
is meant for a whole different purpose then the former two: cutting strings into pieces, rather than assembling. As @Henning noted, it is also "retired" since JDK 1.5 - it is recommended to use String.split
instead.
Difference between String and StringBuffer in java
Yes, new String objects get created for "try"
and "this"
. The benefit here is that the StringBuffer stores the string of characters internally as a dynamically resized array.
It's more obviously beneficial if we were to concatenate more than two Strings:
"try" + "this" + "test"
This would potentially create 5 String objects because you need intermediate values. (Technically concatenation of literals is performed at compile time so this is just a conceptual example.) It would also be typical for a compiler to refactor the above snippet in to using StringBuilder
anyway if they were not literals.
StringBuilder
is a newer and non-synchronized version of StringBuffer
. In general, you should prefer StringBuilder
. The difference between these two classes is covered in "StringBuilder and StringBuffer in Java".
what is the significance of StringBuffer and which should be used more often, StringBuffer or StringBuilder?
In practice everybody should always use StringBuilder (and never use StringBuffer; often you don't really need StringBuilder because the compiler takes care of adding a helper to do this for you). The only reason StringBuffer is still around is for fear that taking it away would break some code somewhere. Java takes backward compatibility really seriously.
The difference between StringBuffer and StringBuilder is that the methods of StringBuffer are synchronized. That means each thread trying to call a synchronized method has to acquire the lock on the object, this prevents problems where two threads calling methods on the same object could result in the object's state becoming corrupted. The backing data store within the object is a dynamically-growing array, and if two threads are messing with it at the same time and one changes it out from under the other, bad things happen: exceptions get thrown, or worse, data gets stomped on silently.
It turns out that there is not a real life need for a string-building object that concatenates strings received concurrently from multiple threads, because nobody wants a string constructed in a way that makes it unpredictable what order the substrings show up in. It's overwhelmingly likely that when you want to construct a string (and have determined you do need a builder) that builder will be thread-confined (meaning only one thread can access the builder), so no synchronization is needed.
what is the difference between StringBuilder and Stringbuffer?
Some methods in StringBuffer are synchronized while StringBuilder is not thread-safe - and faster.
Rule of a thumb - use StringBuilder unless you have a use case, where a StringBuilder is used by more then one Thread (which would be a very rare case).
Difference between String created by String, StringBuilder and StringBuffer
Every class can choose to calculate the hash code in it's own way. Hash codes don't have meaning, and very simple rules (abbreviated):
- Objects where
equals()
return true must return same hash code. - Objects where
equals()
return false should return different hash code, to the best ability of the class, to ensure better performance of hash tables such asHashMap
andHashSet
.
Since a String
with value "ABC"
and a StringBuilder
with value "ABC"
are not equal, there is no requirement that they return the same hash code.
If you extract a String
value from the StringBuilder
, then that string value must have same hash code as another string of the same value, and it will, so the following two expression will return the same value:
new String("ABC").hashCode()
new StringBuilder("AB").append("C").toString().hashCode()
As a side note: Neither StringBuilder
nor StringBuffer
implements equals()
and hashCode()
, so their equality is based on identity, not value. Two StringBuilder
objects with same value will still not be "equal", and will therefore (most likely) not have same hash code.
Related Topics
How to Get the Path of a Running Jar File
What Is the Volatile Keyword Useful For
Why Are Static Variables Considered Evil
Preparedstatement in Clause Alternatives
Converting Json Data to Java Object
How Are Anonymous Inner Classes Used in Java
How to Solve "Java.Lang.Noclassdeffounderror"
How to Read a Large Text File Line by Line Using Java
Java: Splitting a Comma-Separated String But Ignoring Commas in Quotes
How to Read Xml Using Xpath in Java
Setting the Default Java Character Encoding
Retain Precision With Double in Java
How to Get a Class Instance of Generic Type T
Why Is Subtracting These Two Times (In 1927) Giving a Strange Result
String Replace Method Is Not Replacing Characters
Difference Between Jsf, Servlet and Jsp