How to concatenate two strings in java – Java Program to Concatenate Two Strings

How to concatenate two strings in java: Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Java Program to Concatenate Two Strings

  • Java program to concatenate two strings using concat method.
  • Write a java program to append on one string at the end of another string.

In this java program, to concatenate two strings we will first ask user to enter two strings and then concatenate both strings and print it on screen.

For Example,
First String : BTechGeeks
Second String : BTechGeeks
Concatenated String : BTechGeeks
Here we are going to use approaches for string concatenation, first is by calling append() method of StringBuilder class and second is by calling concat() method of String class.

Java program to concatenate two strings using concat and append methods

Java program to concatenate two strings using concat and append methods

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Java Program to Copy a String
 */
public class ConcatenateString {
    public static void main(String args[]) {
        String str1, str2;
        Scanner scanner = new Scanner(System.in);
 
        System.out.println("Enter first String");
        str1 = scanner.nextLine();
 
        System.out.println("Enter second String");
        str2 = scanner.nextLine();
 
        // Concatenating str1 and str2 using String Builder
        StringBuilder str3 = new StringBuilder(str1);
        str3.append(str2);
        System.out.println("Concatenated String : " + str3);
 
        // Concatenating str1 and str2 using concat method
        System.out.println("Concatenated String : " + str1.concat(str2));
    }
}

Output

Enter first String
Tech
Enter second String
CrashCourse
Concatenated String : BTechGeeks
Concatenated String : BTechGeeks