String Concatenation in Java

In this tutorial we will learn how to concatenate multiple strings using concat() method in Java.

public String concat(String str)

This method concatenates the string str at the end of the current string. For e.g. s1.concat("Hello"); would concatenate the String “Hello” at the end of the String s1. This method can be called multiple times in a single statement like this

String s1="Beginners"; s1= s1.concat("Book").concat(".").concat("com");
Complete Example
public class ConcatenationExample { public static void main(String args[]) { //One way of doing concatenation String str1 = "Welcome"; str1 = str1.concat(" to "); str1 = str1.concat(" String handling "); System.out.println(str1); //Other way of doing concatenation in one line String str2 = "This"; str2 = str2.concat(" is").concat(" just a").concat(" String"); System.out.println(str2); } }

Welcome to String handling This is just a String

In java, string concatenation forms a new string that is the combination of multiple strings. There are two ways to concat string in java:

  1. By + (string concatenation) operator
  2. By concat() method
1) String Concatenation by + (string concatenation) operator
class TestString{ public static void main(String args[]){ String s="Rama"+" Krishna"; System.out.println(s);//Sachin Tendulkar } }

Rama Krishna

The Java compiler transforms above code to this:

String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();

In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and its append method. String concatenation operator produces a new string by appending the second operand onto the end of the first operand. The string concatenation operator can concat not only string but primitive values also.

class TestString{ public static void main(String args[]){ String s=31+36+"Rama"+36+31; System.out.println(s);//80Sachin4040 } }

2) String Concatenation by concat() method
public String concat(String another)
class TestString{ public static void main(String args[]){ String s1="Rama "; String s2="Krishna"; String s3=s1.concat(s2); System.out.println(s3);//Sachin Tendulkar } }

Rama Krishna