How to Concatenate two Strings using concat() Method in Java? | String Concatenation in Java with Example

In this tutorial, we will be learning about how to concatenate two strings in Java by using concat() method of the String class. Along with the definition of the java string concat() methods, you can also see the signature and example of the string concatenation in java. Look at the direct links available here and make use of them for quick reference.

Java String Concat() Method

Java string concat() method concatenates multiple strings. However, it concatenates the defined string to the end of this string. If the length argument of the string is 0 then this string object is returned otherwise a new string object is created.

Internal implementation of String concat method

public String concat(String str) { 
int otherLen = str.length(); 
if (otherLen == 0) { 
return this; 
} 
int len = value.length; 
char buf[] = Arrays.copyOf(value, len + otherLen); 
str.getChars(buf, len); 
return new String(buf, true); 
}

The concat() method signature

The syntax of the concat() method in java is given below:

public String Concat(String str)

Parameter

Here

  • str: defines the string to be concatenated at the end of another string.

Return Value 

It returns the combination of two strings.

Read More:

Example of String Concatenation by concat() Method

We can concatenate the two strings by using the Concat() method. It returns the newly created string object. Let’s see the following Java program to concatenate two strings using the concat method:

public class ConcatExample{ 
public static void main(String args[]){ 
String s1="java string"; 
s1.concat("is immutable"); 
System.out.println(s1); 
s1=s1.concat(" is immutable so assign it explicitly"); 
System.out.println(s1); 
}}

Output:

java string
java string is immutable so assign it explicitly