This post will discuss how to concatenate multiple strings in Java using the + operator, String.concat() method, and append() method of the StringBuffer/StringBuilder class.

String concatenation is one of the most common operations in Java, and it can easily become a performance nightmare if not done properly. This post will discuss various methods to concatenate multiple strings in Java and compare their performance.

1. Using StringBuilder.append() method

StringBuilder class is trendy among Java developers and recommended concatenating multiple strings in Java as it outperforms all other performance methods. It provides append() methods, which are overloaded to accept data of any type.

 
We should use the StringBuilder class to prefer the StringBuffer class as it will be faster under most implementations since it is not thread-safe. We should only use the StringBuffer class when thread-safety is required, which is rarely the case.

2. Using + Operator

Another widely used method to concatenate multiple strings in Java is to use the + operator. It is straightforward to use, but we should actually avoid it as it offers the worst performance, almost several hundred times slower than StringBuilder or StringBuilder class.

Since the + operator is internally translated to StringBuilder by the compiler, we can also use it to concatenate the string with other datatypes such as an integer, long, double, etc.

3. Using String.concat() method

We can also use concat() method provided by String class that generally uses Arrays.copyOf() and System.arraycopy() method internally. This approach also falls short in terms of performance for multiple strings and should not be preferred over StringBuilder.

That’s all about concatenating multiple strings in Java.