Skip to content

Java String Concatenate Example

Java String Concatenate example shows how to concatenate strings in Java. The example also shows the difference between concatenation operator (+) vs concat method vs concatenation using StringBuilder/StringBuffer.

How to concatenate strings in Java?

There are several ways using which you can concatenate String in Java as given below.

1) Concatenate String using the concatenation operator (+)

You can use the string concatenation operator “+” to concatenate two or more Strings as given below.

Output

Concatenation using the + operator also works with Objects and primitive values. If the object is concatenated with the String, it is automatically converted to String using the toString method of it. Primitive values are also converted to a string representation using the respective wrapper class’s toString method. It even concatenates null without throwing NullPointerException.

Output

2) Concatenate String using the concat method of String class

You can use concat method of String class to concatenate two strings as given below.

Output

3) Concatenate String using the StringBuffer or StringBuilder class

StringBuffer or StringBuilder can be used to concatenate multiple strings using the append method as given below.

Output

What is the best way to concatenate strings?

Difference between String concatenation using + operator, the concat method, and StringBuffer

1) Concatenating strings using the + operator looks clean and clearly shows the purpose of the expression than concatenation using the concat method. Moreover, concatenation using the + operator might use the String objects from the pool, while String concatenation using the concat method always create a new String object.

2) String concatenation using the + operator is converted to a more efficient code which uses the append method of the StringBuffer/StringBuilder class by the most modern JVMs as given below.

Will be converted to

3) The concat method only works with strings. You can not append other data types, such as primitive values using it. While the + operator works with all of them.

4) If the first string is null, invoking the concat method on it will throw NullPointerException exception. Concatenating them with the + operator will not throw the exception as given in the below example.

Will print

If the number of concatenation operations is small, concatenation using the + operator is recommended. On the other hand, if you need to do concatenate operation in a loop, using the append method of StringBuffer class gives more performance.

This example is a part of the Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.