Sunday, 25 September 2016

Java - String, StringBuilder & String Buffer


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 StringStringBuffer 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 not synchronized one.
  • In case the Object value can change, and will be modified by multiple threads, use a StringBuffer because StringBuffer is synchronized.
The main idea is that String is immutable. So when you are trying to modify it, new object created. StringBuffer and StringBuilder are mutable. And the difference is the first one is thread-safe.
The common approach to using StringBuilder is to parse something when you iteratively create a String object in a NON thread safe environment.
For example, you have a numbers array [1, 2, 3]. To create object "String1String2String3" you can use a StringBuilder
StringBuilder builder = new StringBuilder();
foreach(Integer num : array) {
    builder.append("String").append(num);
}
builder.toString();
It's better than just using String string = string + ("String" + num);. AFAIK, compiler will optimize using string concatenation in the loop to StringBuilder, but better to use it manually.
StringBuffer is used when you have shared states, that are modified by concurrent threads.
Courtesy & Source:
http://stackoverflow.com/a/11273836
http://stackoverflow.com/a/11273893

No comments: