I\'m trying to understand what the best practice is and why for concatenating string literals and variables for different cases. For instance, if I have code like this
The compilier optimize the + concatenation.
So
int a = 1;
String s = "Hello " + a;
is transformed into
new StringBuilder().append("Hello ").append(1).toString();
There an excellent topic here explaining why you should use the + operator.
I personally prefer the Strings.format()
, simple easy to read one-line string formatter.
String b = "B value";
String d = "D value";
String fullString = String.format("A %s C %s E F", b, d);
// Output: A B value C D value E F
You should always use append
.
concat
create a new String so it's pretty like +
I think.
If you concat
or use +
with 2 final String the JVM can make optimisation so it's the same as doing append in this case.