Concatenate Two Strings in Java Without Using + Operator
String concatenation means joining two strings to form a single string.
Although Java provides the + operator and concat() method,
learning to concatenate strings manually helps understand how strings work internally.
In this program, we concatenate two strings by:
- Converting both strings into character arrays
- Copying characters into a new array
- Creating a new string from the combined characters
How the Logic Works
- Read two input strings.
- Create a character array with combined length.
- Copy characters of the first string.
- Append characters of the second string.
- Convert the character array into a string.
Example 1
String 1: "Hello"
String 2: "World"
Result: HelloWorld
Example 2
String 1: "Java "
String 2: "Programming"
Result: Java Programming
Java Program to Concatenate Two Strings Without Using +
import java.util.Scanner;
public class ConcatenateStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = sc.nextLine();
System.out.print("Enter second string: ");
String str2 = sc.nextLine();
char[] result = new char[str1.length() + str2.length()];
int index = 0;
for (int i = 0; i < str1.length(); i++) {
result[index++] = str1.charAt(i);
}
for (int i = 0; i < str2.length(); i++) {
result[index++] = str2.charAt(i);
}
String finalString = new String(result);
System.out.println("Concatenated String: " + finalString);
}
}
Sample Output
Enter first string: Good
Enter second string: Morning
Concatenated String: GoodMorning
Important Notes
- No
+operator is used for concatenation. - This approach avoids built-in string concatenation methods.
- Time complexity is O(n + m).
Practice Challenges
- Concatenate multiple strings using the same logic.
- Concatenate two strings without using arrays.
- Insert a space automatically between the two strings.
Manual string concatenation strengthens your understanding of memory handling and string processing in Java.