Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning in StringBuffer and StringBuilder

Tags:

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(" "); 
like image 845
Abish R Avatar asked Mar 30 '17 03:03

Abish R


People also ask

What is the main difference between StringBuffer and StringBuilder?

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.

Is StringBuffer or StringBuilder thread-safe?

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.

Which is more efficient StringBuilder or StringBuffer?

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.

How is StringBuffer thread-safe?

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.


1 Answers

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... 
like image 170
GhostCat Avatar answered Oct 13 '22 23:10

GhostCat