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(" ");
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...