Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always a bad idea to use + to concatenate strings

I have code as follows :

String s = "";
for (My my : myList) {
    s += my.getX();
}

Findbugs always reports error when I do this.

like image 802
fastcodejava Avatar asked Oct 01 '10 00:10

fastcodejava


People also ask

Why can't I concatenate a string?

The typical issue brought up for string concatenation revolves around a few issues: The first and foremost issue with using + for string concatenation and addition is that you're using + for string concatenation and addition. if you have variables a and b, and you set c = a + b, there is an ambiguity dependent on the types of a and b.

Should I use StringBuilder or StringBuffer for concatenation?

String.concat beats + performance-wise. Use StringBuilder when you need to concatenate strings in a loop. StringBuffer helps with thread-safe concatenation, and performs the same as StringBuilder. For more up-to-date String quirks check out my recent article.

Is it bad to use + for both addition and concatenation?

It's not bad to use + for both addition and concatenation, as long as you can only add numbers, and only concatenate strings. However, Javascript will automatically convert between numbers and strings as needed, so you have: 3 * 5 => 15 "3" * "5" => 15 2 + " fish" => "2 fish" "3" + "5" => "35" // hmmm...

Why does PHP use + for string concatenation?

Not all languages use + for string concatenation. PHP uses . to concatenate strings, which helps distinguish between when you want to add numbers and when you want to join strings. Any symbol could be used to concatenate strings, but most are already used, and it's best to avoid duplication.


1 Answers

I would use + if you are manually concatenating,

String word = "Hello";
word += " World!";

However, if you are iterating and concatenating I would suggest StringBuilder,

StringBuilder sb = new StringBuilder();
for (My my : myList) {
    sb.append(my.getX());
}
like image 70
Anthony Forloney Avatar answered Nov 13 '22 12:11

Anthony Forloney