Java – String concat() Method

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

Internal implementation
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); }
Signature

The signature of string concat() method is given below:

public String concat(String anotherString)
Parameter

anotherString : another string i.e. to be combined at the end of this string.

Returns

combined string

Example
public class Test1 { 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); } }


Output:
Welcome to String handling This is just a String
Java String concat() method example
public class Text { 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
Java String concat() Method Example

See an example where we are concatenating multiple string objects.

public class Test { public static void main(String[] args) { String str1 = "Hello"; String str2 = "Rama"; String str3 = "krishna"; // Concatenating one string String str4 = str1.concat(str2); System.out.println(str4); // Concatenating multiple strings String str5 = str1.concat(str2).concat(str3); System.out.println(str5); } }


Output:
HelloRama HelloRamakrishna
Java String concat() Method Example
public class Test1 { public static void main(String[] args) { String str1 = "Hello"; String str2 = "Rama"; String str3 = "krishna"; // Concatenating Space among strings String str4 = str1.concat(" ").concat(str2).concat(" ").concat(str3); System.out.println(str4); // Concatenating Special Chars String str5 = str1.concat("!!!"); System.out.println(str5); String str6 = str1.concat("@").concat(str2); System.out.println(str6); } }


Output:
Hello Rama krishna Hello!!! Hello@Rama



Instagram