Java String concat() Method

String concatenation is the process of combining two or more small String to create a bigger String. In Java you can combine string in multiple ways. Using + operator is the easiest way of joining multiple String. Also you can use String.concat() method to joining two strings in Java. But to improve performance, instead of using + operator or String.concat(), use StringBuffer is better choice. All method of concatenating string is following:

Using + operator

You can concatenate Strings in Java using the + operator.

String str = "Java " + "String " + "Tutorial";

Above code will return "Java String Tutorial"

Example
class TestClass{ public static void main (String[] args){ String str = "Java " + "String " + "Tutorial"; System.out.println(str); String str1 = "Java "; String str2 = "String "; String str3 = "Tutorial"; String result = str1 + str2 + str3; System.out.println(result); } }
Output
Java String Tutorial Java String Tutorial

Using StringBuffer

In order to improve performance StringBuffer is the better choice.

The quickest way of concatenate two string using + operator.

String str = "Java"; str = str + "Tutorial";

The compiler translates this code as:

String longStr = "Java"; StringBuffer tmpSb = new StringBuffer(longStr); tmpSb.append("Tutorial"); longStr = tmpSb.toString();
Main reason of performance drop is creation of lots of temporary String object due to immutability of String. Just remember that String concatenation using + operator is also converted to corresponding StringBuffer or StringBuilder call depending upon which version of Java you are using, because StringBuilder is only available from Java 1.5 . So the best approach is to use StringBuffer.
String str = new StringBuffer().append("first").append("second").append("third").toString();

Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Example
class TestClass{ public static void main (String[] args){ String first = "Java "; String second = "String "; String third = "Tutorial"; StringBuffer str = new StringBuffer(); str.append(first); str.append(second); str.append(third); System.out.println(str); } }

Using Java String concat() method

Java String Concat(String str) method concatenates the specified String to the end of this string.

Example
class TestClass{ public static void main (String[] args){ String first = "Java "; String second = "Tutorial "; String str = first.concat(second); System.out.println(str); } }