The two are functionally the same. Meaning they perform the same task. They are quite different in how they operate behind the scenes.
String concatenation with the +
operator will take marginally longer to process because of what happens when it's compiled into bytecode. Without delivering the bytecode here is the code equivalent of concatenation compiled:
// Concatenation
String a = "a";
String b = "b";
a = a + b;
// It's equivalent once it's compiled
String a = "a";
String b = "b";
StringBuilder aBuilder = new StringBuilder(a);
aBuilder.append(b);
a = aBuilder.toString();
As you can see, even though no usage of a StringBuilder
is present in the concatenation snippet a StringBuilder
is still created and used. This is why (mostly for large data sets where the time will be noticeable) you should avoid concatenation to avoid the need for firing up String builders like this. Just use a builder from the beginning:
StringBuilder a = new StringBuilder("a");
a.append("b");
System.out.println(a);
And you'll save yourself some execution time and memory.