Warning in StringBuffer and StringBuilder

Abish R picture Abish R · Mar 30, 2017 · Viewed 8.1k times · Source

I have a StringBuffer initialized outside for loop and inside for loop I am concatenating some strings.

I am getting the warning

'StringBuffer stringBuffer' may be declared as 'StringBuilder'

and

string concatenation as argument to 'stringbuilder.append()' call

Then I changed that StringBuffer to StringBuilder, since it is comparatively faster than StringBuffer. Now I am getting the warning as

string concatenation as argument to 'stringbuilder.append()' call

Sample code:

public static String stringConcat(String[] words) {
    StringBuffer stringBuffer = new StringBuffer();
    for (String word : words) {
        stringBuffer.append(word).append(" ");
    }
    return stringBuffer.toString();
}

Why I am getting these warnings.

Edit Actual code:

stringBuffer.append(word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()).append(" ");

Answer

GhostCat picture GhostCat · Mar 30, 2017

The point is : you are still using the + operator for strings in your expression that you give to append():

... word.substring(0, 1).toUpperCase() + word...

That negates the whole point of using a StringBuilder (or StringBuffer).

Instead: simply call append() twice! The core idea of using a buffer/builder is to concat your desired result by only using append calls; like:

append(word.substring(0, 1).toUpperCase()).append(word...