13. Concatenating strings versus StringBuilder
Check out the following plain string concatenation:
String str1 = "I love";
String str2 = "Java";
String str12 = str1 + " " + str2;
We know that the String
class is immutable (a created String
cannot be modified). This means that creating str12
requires an intermediary string that represents the concatenation of str1
with white space. So after str12
is created, we know that str1 + " "
is just noise or garbage, since we cannot refer to it further.
In such scenarios, the recommendation is to use a StringBuilder
, since it is a mutable class and we can append strings to it. So this is how the following statement was born: In Java, don’t use the “+
" operator to concatenate strings! Use StringBuilder
, which is much faster.
Have you heard this statement before? I’m pretty sure you have, especially if you still run your applications on JDK 8 or even on a previous...