Search code examples
javastringappendsonarqubestringbuffer

Using String Buffer For String Appends in Java


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.


Solution

  • 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.