In java String Builder Should be Used in case you need to perform concatenate more string together.

i.e

 public String toString()
 {
    return  a + b + c ;
 }

For the above code using + will be converted to

a = new StringBuilder()
    .append(a).append(b).append(c)
    .toString();

For the above case you can use concat as below but since + will be converted as String Builder its better to use + rather than concat.

 public String toString()
 {
    return  a.concat(b).concat(c);
 }

The key is whether you are writing a single concatenation all in one place or accumulating it over time.

There's no point in explicitly using StringBuilder.

But if you are building a string e.g. inside a loop, use StringBuilder.

To clarify, assuming that hugeArray contains thousands of strings, code like this:

...
String result = "";
for (String s : hugeArray) {
    result = result + s;
}

It should be as below

 ...
StringBuilder sb = new StringBuilder();

for (String s : hugeArray) {
    sb.append(s);
}
String result = sb.toString();

Leave a reply