Tuesday, 15 January 2013

String vs StringBuffer vs StringBuilder


The main difference between the three most commonly used String classes as follows.
  • StringBuffer and StringBuilder objects are mutable whereas String class objects are immutable.
  • StringBuffer class implementation is synchronized while StringBuilder class is not synchronized. 
Note: If you keep forgetting which one is synchronized which one is not remember StringBuilder is just implmentation of builder pattern so the other is Synchronized which is StringBuffer
  • Concatenation operator "+" is internally implemented by Java using StringBuilder.
Note: For more details see this link

Criteria to choose among String, StringBuffer and StringBuilder
  • If the Object value will not change in a scenario use String Class because a String object is immutable.
  • If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster).
  • If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).

No comments:

Post a Comment