Write a Java program to Concat Strings with an example. There are multiple ways to perform string concatenation, and we cover most of them. We can use the built-in functions, including concat, StringBuilder, and StringBuffer append functions. Apart from these, use the arithmetic + operator to achieve the same.
Java Program to Concat Strings
In this Java example, we used the String function to concat con_str2 to the con_str1 and assigned the output to a new one, str3.
import java.util.Scanner; public class Example { private static Scanner sc; public static void main(String[] args) { String con_str1; String con_str2; sc= new Scanner(System.in); System.out.print("\nPlease Enter the first : "); con_str1 = sc.nextLine(); System.out.print("\nPlease Enter the second : "); con_str2 = sc.nextLine(); String str3 = con_str1.concat(con_str2); System.out.println("\nThe result = " + str3); } }
Please Enter the first : Hi
Please Enter the second : Hello
The result = HiHello
Using Assignment Operator +
In this Program, we used the Assignment Operator + for String concatenation. By default, the + operator will concat the given strings. However, to add the space between the two words, you must use the ‘ ‘ between the words.
import java.util.Scanner; public class ConcatStrings1 { private static Scanner sc; public static void main(String[] args) { String conStr1; String conStr2; sc= new Scanner(System.in); System.out.print("\nPlease Enter the first String : "); conStr1 = sc.nextLine(); System.out.print("\nPlease Enter the second String : "); conStr2 = sc.nextLine(); String str3 = conStr1 + ' ' + conStr2; System.out.println("\nThe Java String concat result = " + str3); } }

Java Program to Concat Strings using StringBuilder
The StringBuilder has an append function that appends one string at the end of the other one.
import java.util.Scanner; public class Example2 { private static Scanner sc; public static void main(String[] args) { String conStr1; String conStr2; sc= new Scanner(System.in); System.out.print("\nPlease Enter the first : "); conStr1 = sc.nextLine(); System.out.print("\nPlease Enter the second : "); conStr2 = sc.nextLine(); StringBuilder sb = new StringBuilder(15); sb.append(conStr1).append(" ").append(conStr2); System.out.println("\nThe result = " + sb.toString()); } }

Using StringBuffer append
The StringBuffer also has an append function that concat one string to the end of the other.
import java.util.Scanner; public class Example3 { private static Scanner sc; public static void main(String[] args) { String conStr1; String conStr2; sc= new Scanner(System.in); System.out.print("\nPlease Enter the first : "); conStr1 = sc.nextLine(); System.out.print("\nPlease Enter the second : "); conStr2 = sc.nextLine(); StringBuffer sbuff = new StringBuffer(15); sbuff.append(conStr1).append(" ").append(conStr2); System.out.println("\nResult = " + sbuff.toString()); } }
