I was just going through the net but I could not find a clear & precise
difference between
String
,StringBuilder
&StringBuffer
.Please also explain when should we use them and what do we mean by
thread-safe
in java ?
I was just going through the net but I could not find a clear & precise
difference between
String
,StringBuilder
&StringBuffer
.Please also explain when should we use them and what do we mean by
thread-safe
in java ?
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.
Main difference between String and StringBuilder/StringBuffer is that String is immutable, i.e. a String you once have initialized cannot be changed anymore. Redefining a String just creates a new immutable String in memory. Instances of StringBuilder/StringBuffer can be modified by methods like append(String str) or insert(StringBuffer sb). The only difference between StringBuilder/StringBuffer is that StringBuilder is not safe for use by multiple threads, StringBuffer instead is thread-safe.
So if you want to use string objects that you define once and do not need to modify a lot, you use String. If you want to work on them you use StringBuilder, and if you want to do this in a multithreaded environment you use StringBuffer.