Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to use StringBuffer/StringBuilder than String [duplicate]

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.

like image 962
Soumyadip Das Avatar asked Jun 30 '12 11:06

Soumyadip Das


1 Answers

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.
like image 179
user370305 Avatar answered Nov 01 '22 06:11

user370305