Where to use StringBuffer/StringBuilder than String

android, java, string, stringbuilder

Solution

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.

Problem

Possible Duplicate: String, StringBuffer, and StringBuilder We know that `String` are immutable where `StringBuffer`/`StringBuilder` are mutable. But sometimes we get confused what to use in our code.. the String or StringBuffer/StringBuilder ?? Practically in our maximum code/quick code we use to prefer `String` than `StringBuffer`/`StringBuilder`. This question is to solve the confusion, if you have any idea & proper reason for that, then please give a reply.

Original source

Related problems