I have code as follows :
String s = "";
for (My my : myList) {
s += my.getX();
}
Findbugs always reports error when I do this.
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.
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.
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...
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.
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());
}
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