Thursday, March 26, 2015

When to Use String/StringBuilder/String Buffer during Concatenation

When you want the String concatenation to be done at compile time, then you can use the normal '+' operator, otherwise String.concat() to do it. This is efficient at the compile time.

But when you are using the concatenation at the run time, you have to do it using StringBuilder or String Buffer. 

We have to identify the difference between these two. StringBuilder is NOT Synchronized and StringBuffer is Synchronized. Therefore when you want to work in a thread safe environment you have to use StringBuffer. Otherwise you have to use the StringBuilder. That would make the concatenation faster at runtime. 

References :