Concatenate Multiple Strings in Java

In this post, we will discuss how to concatenate multiple Strings in Java using + operator, String.concat() method and StringBuffer, StringBuilder append() method.

 
 
String concatenation is one of the most common operation in Java and it can easily become a performance nightmare if not done properly. In this post, we will discuss various methods to concatenate multiple Strings in Java and also compare their performance.

 

1. Using append() method of StringBuilder or StringBuffer

StringBuilder class is very popular among Java developers and recommended way to concatenate multiple Strings in Java as it outperforms all other methods in terms of performance. It provides append() methods, which are overloaded so as to accept data of any type.

 
StringBuilder class should used in preference to StringBuffer class as it will be faster under most implementations since it is not thread-safe. We should only use 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 + operator. It is very easy to use but we should actually avoid it as it offers worst performance, almost several hundred times slower than StringBuilder or StringBuilder class.

Since + operator is internally translated to StringBuilder by the compiler, we can also use it to concatenate 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 fall short in terms of performance for multiple strings and should not be preferred over StringBuilder.

 

 
 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz