Search code examples
javastringinternationalizationcoding-style

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.


Solution

  • 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());
    }