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(" ");
String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer.
StringBuffer is synchronized and therefore thread-safe. StringBuilder is compatible with StringBuffer API but with no guarantee of synchronization. Because it's not a thread-safe implementation, it is faster and it is recommended to use it in places where there's no need for thread safety.
StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
StringBuffer is thread-safe meaning that they have synchronized methods to control access so that only one thread can access StringBuffer object's synchronized code at a time.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With