The compiler will optimize the code to equal this:
String a = "JavaVirtualMachine";
The more interesting question is probably what this does:
int x = 5;
String a = "foo" + x + "bar";
In which case the compiler will create a StringBuilder
and append all values.
This would roughly translate to this code:
int x = 5;
String a = new StringBuilder().append("foo").append(x).append("bar").toString();
But if you are concatenating String
s in a loop, the compiler will create a StringBuilder
in each iteration. So if you have a code like this:
String[] errorMessages = getErrorMessages();
String output = "Found the following error messages:";
for(int i = 0; i < errorMessages.length(); i++){
output += "\n" + (i+1) + ": " + errorMessages[i];
}
This would translate (again roughly) to:
String[] errorMessages = getErrorMessages();
String output = "Found the following error messages:";
for(int i = 0; i < errorMessages.length();
output = new StringBuilder(output).append('\n')
.append((i+1)).append(": ").append(errorMessages[i]).toString();
}
Like mentioned, this creates a new StringBuilder
in each iteration. So in these cases it is better not to rely on the compiler to do it's magic, create your own StringBuilder
, and use the same object throughout the whole iteration:
String[] errorMessages = getErrorMessages();
StringBuilder builder = new StringBuilder("Found the following error messages:");
for(int i = 0; i < errorMessages.length(); i++){
builder.append('\n').append((i+1)).append(": ").append(errorMessages[i]);
}