Friday, 4 September 2015

What is difference between String, StringBuffer and StringBuilder? When to use them?

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.
  • Concatenation operator "+" is internally implemented by Java using either StringBuffer or StringBuilder.

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