Concatenate two strings in Java

Google Translate Icon

This post will discuss how to concatenate two Java strings using the + operator, StringBuffer, StringBuilder, and concat() method provided by java.lang.String class.

1. Using + Operator

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

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

new StringBuilder().append("Techie").append(" ").append("Delight").toString()

2. Using String.concat() method

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

3. Using StringBuilder or StringBuffer

StringBuilder is a 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 the + operator, StringBuilder will work with several data types as the append() method is overloaded to accept an Object, StringBuilder, CharSequence, char[], boolean, char, int, long, float, and double.

StringBuffer is almost similar to StringBuilder, except all methods are 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 the most common operation in the Java programming language and can easily become a performance nightmare if not done wisely. Let’s now determine which method gives us the 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 the + operator and concat() method in Java. It also performs better than StringBuffer because of the overhead caused by the thread-safety of StringBuffer.

That’s all about concatenating two strings in Java.

Rate this post

Average rating 4.31/5. Vote count: 26

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?




Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding :)



Subscribe
Notify of
guest
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Do NOT follow this link or you will be banned from the site!