Java Program to Concatenate Two Strings

Here is a Java program to concatenate two strings using concat method. 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 : Tech
Second String : CrashCourse
Concatenated String : TechCrashCourse

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

package com.tcc.java.programs;

import java.util.Scanner;


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 : TechCrashCourse
Concatenated String : TechCrashCourse

Recommended Posts
Java Program to Find Length of a String
Java Program to Delete All Spaces from a String
Java Program to Copy a String
Java Program to Reverse a String
Java Program to Count Words in a Sentence
Java Program to Reverse Sequence of Words of a Sentence
Java Program to Check Two Strings are Anagram or Not
Java Program to Delete all Vowel Characters from String
Java Program to Print Pascal Triangle
Java Program to Check Whether two Strings are Equal or Not
Java Program to Delete a Word from Sentence
All Java Programs