String Concatination

  • Take readability into account
  • The compiler does some optimizations
    • depends on java version
    • hand crafted optimizations can not be optimized by the compiler later
  • Whenever possible use +
  • Note that an assignement creates a new string instance
    • do not use s = s + “someString” or similar in a loop

Pre Java 9

String m(String a, int b) {
  return a + "(" + b + ")";
}

The compiler generates somthing like

String m(String a, int b) {
  return new StringBuilder().append(a).append("(").append(b).append(")").toString();
}

References