Concatenate multiple strings in Java
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.
|
1 2 3 4 5 6 7 8 9 10 |
// Method to concatenate multiple strings in Java using the `+` operator public static String concatenate(String... s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length; i++) { sb = sb.append(s[i]); } return sb.toString(); } |
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.
|
1 2 3 4 5 6 7 8 9 10 |
// Method to concatenate multiple strings in Java using the `+` operator public static String concatenate(String... s) { String res = ""; for (int i = 0; i < s.length; i++) { res = res + s[i]; } return res; } |
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.
|
1 2 3 4 5 6 7 8 9 10 |
// Method to concatenate multiple strings in Java using the `+` operator public static String concatenate(String... s) { String res = ""; for (int i = 0; i < s.length; i++) { res = res.concat(s[i]); } return res; } |
That’s all about concatenating multiple strings in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)