Concatenate Two Strings in Java

In this post, we will see how to concatenate two Strings in Java using + operator, StringBuffer, StringBuilder and concat() method provided by java.lang.String class.

 

1. Using + Operator

The + operator is one of the easiest way to concatenate two Strings in Java that is used by vast majority of Java developers. We can also use it to concatenate string with other datatypes such as an integer, long, etc.

Please note that the compiler internally translates the + operator into chains of StringBuilder.append() method, followed by a call to StringBuilder.toString() method that converts the StringBuilder back to the String object. For instance,

is translated to

 

2. Using String.concat() method

We can also use concat() method to concatenate one string to the end of another string. It internally uses Arrays.copyOf() and System.arraycopy() method.

 

3. Using StringBuilder or StringBuffer

StringBuilder is widely used and recommended way to concatenate two Strings in Java. It is mutable unlike String, meaning that we can change the value of the object.

Like + operator, StringBuilder will work with several data types as append() method is overloaded to accept an Object, StringBuilder, CharSequence, char[], boolean, char, int, long, float and a double.

StringBuffer is almost similar to StringBuilder, except all methods is synchronized in it i.e. StringBuffer is thread safe. We should only use it when thread-safety is required, which is rarely the case.

 

Performance –

String concatenation is most common operation in Java programming language and can easily become a performance nightmare if not done wisely. Let us now determine which method gives us best performance for String concatenation.

 
We should always use StringBuilder to concatenate Strings in Java. It outperforms all other methods in terms of performance. We can easily test that it is several hundred times faster than + operator and concat() method in Java. It also performs better than StringBuffer because of overhead caused by thread-safety of StringBuffer.

 
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