Using String
concatenation is translated into StringBuilder
operations by the compiler.
To see how the compiler is doing I’ll take a sample class, compile it and decompile it with jad to see what’s the generated bytecode.
Original class:
public void method1() {
System.out.println("The answer is: " + 42);
}
public void method2(int value) {
System.out.println("The answer is: " + value);
}
public void method3(int value) {
String a = "The answer is: " + value;
System.out.println(a + " what is the question ?");
}
The decompiled class:
public void method1()
{
System.out.println("The answer is: 42");
}
public void method2(int value)
{
System.out.println((new StringBuilder("The answer is: ")).append(value).toString());
}
public void method3(int value)
{
String a = (new StringBuilder("The answer is: ")).append(value).toString();
System.out.println((new StringBuilder(String.valueOf(a))).append(" what is the question ?").toString());
}
- On
method1
the compiler performed the operation at compile time. - On
method2
theString
concatenation is equivalent to manually useStringBuilder
. - On
method3
theString
concatenation is definitely bad as the compiler is creating a secondStringBuilder
rather than reusing the previous one.
So my simple rule is that concatenations are good unless you need to concatenate the result again: for instance in loops or when you need to store an intermediate result.