2

I would like to know if this use of StringBuffer does the same thing as my previous code, because SonarQube asks me not to use += for appending strings.

My previous code :

String sign = "";
if (value < 0) {
    sign.append("-");
}

My new code with StringBuffer :

StringBuffer sign = new StringBuffer();
sign.append("");
if (value < 0) {
    sign.append("-");
}

Is this better this way ?

Thanks for your advices.

hacks4life
  • 691
  • 5
  • 16
  • 38

3 Answers3

2

Unless you are using that code in a loop, there no bad in your first way (String concatination). For a single attempt you can use that.

As someone commented I assume by writing sign.append("-");, you mean sign +="-"

If you are using in a loop I suggest to use StringBuilder instead of StringBuffer since there is another overhead with StringBuffer is it is synchronized. Unless you need Thread safety, better to change it to StringBuilder.

I'm not sure why SonarQube suggest you to use StringBuffer.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

StringBuffer is better approach that String Concatenation.

Because It will give better memory utilization.

Siva Kumar
  • 1,983
  • 3
  • 14
  • 26
0

Yes, it's better way, but StringBuffer is slower than StringBuilder, but synchronized.
If you are using this code is not in a multithreaded application I recommend you use StringBuilder.

viartemev
  • 211
  • 1
  • 4
  • 13