Java Program to concatenate two string.
Objective
Write a Java program to concatenate (join) two strings together.
Algorithm / Approach
- Read the first string from the user and store it in
s1. - Read the second string from the user and store it in
s2. - Use the
concat()method:s1.concat(s2)to join them. - Store the returned result in a third string
s3. - Print the concatenated string.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter 1st String: ");
String s1=s.nextLine();
System.out.print("Enter 2nd String: ");
String s2=s.nextLine();
String s3=s1.concat(s2);
System.out.print("Concat. String: "+s3);
}
}
Expected Output
Enter 1st String: Java Enter 2nd String: Prowess Concat. String: JavaProwess
Explanation of the Program
- Concatenation is the process of appending one string to the end of another.
- Java provides multiple ways to concatenate strings. You can use the built-in
concat()method as shown here, or simply use the+operator (e.g.,s1 + s2). - Remember that strings are immutable. The
concat()method doesn't changes1; instead, it creates and returns a brand new string containing the combined text.
Complexity
Time Complexity
O(n + m) - Where n and m are the lengths of the two strings.
Space Complexity
O(n + m) - To create the new concatenated string object.