Alex Rivera | Logout

Where to use StringBuffer/StringBuilder than String

Asked 2012-06-30T11:46:50.370
18

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.

Edit
Report

1 Answer

4

The main idea is that String is immutable. So when you are trying to modify it, new object created. StringBuffer and StringBuilder are mutable. And the difference is the first one is thread-safe.

The common approach to using StringBuilder is to parse something when you iteratively create a String object in a NON thread safe environment.

For example, you have a numbers array [1, 2, 3]. To create object "String1String2String3" you can use a StringBuilder

StringBuilder builder = new StringBuilder();
foreach(Integer num : array) {
    builder.append("String").append(num);
}
builder.toString();

It's better than just using String string = string + ("String" + num);. AFAIK, compiler will optimize using string concatenation in the loop to StringBuilder, but better to use it manually.

StringBuffer is used when you have shared states, that are modified by concurrent threads.

answered 2012-06-30T11:58:11.180

Your Answer