How to Combine Two Strings Character by Character in Java

🔡 Combination of Characters in Java :- In this program, I explored how to combine two strings character by character to form a single merged string. This simple concept strengthens our understanding of string manipulation, loops, and conditional checks in Java. 💡 Concept Explanation:- The goal is to merge two strings alternately, taking one character from each string until both are fully combined. 📘 Example:- String 1: Codegnan String 2: Destination Output: CDoedsetginnaatni 👉 The program picks one character from the first string, then one from the second, and so on — until both strings are finished. 🧩 Detailed Explanation of the Code:- 1️⃣ Method Definition public static void combination(String str1, String str2) This method takes two strings as input and combines them. 2️⃣ Find the Maximum Length int length1 = str1.length(); int length2 = str2.length(); int maxlength = length1 > length2 ? length1 : length2; We find the maximum length so that the loop runs long enough to include all characters from both strings — even if one is longer than the other. 3️⃣ Use StringBuffer for Efficiency StringBuffer sb = new StringBuffer(); StringBuffer is used because it is mutable — meaning it can efficiently modify and append characters during the loop. 4️⃣ Character-by-Character Combination for (int i = 0; i < maxlength; i++) { if (i < str1.length()) { sb.append(str1.charAt(i)); } if (i < str2.length()) { sb.append(str2.charAt(i)); } } ✅ Explanation: The loop runs until the longest string’s end. For each index: If that index exists in the first string → add its character. If that index exists in the second string → add its character. This way, characters from both strings are merged alternately. 5️⃣ Print the Result System.out.println(sb); The combined string is printed after both strings have been fully processed. 🧠 Example Outputs: combination("Codegnan","Destination"); → CDoedsetginnaatni combination("Sachin","Tendulkar"); → STaecnhdiunlkar combination("Vijayawada","Challapalli"); → VCihjaallyaawpadalli combination("Chandu","Arepalli"); → CAhranedpuallli ✅ Key Concepts Used:- String manipulation using charAt() Loops for iteration Conditional logic for different string lengths StringBuffer for performance This program enhances understanding of string handling, logic building, and clean code design in Java — all essential for real-world development. ✨ Special thanks to my mentors Anand Kumar Buddarapu for their constant guidance and encouragement throughout my learning journey. #Java #Coding #Programming #StringManipulation #LogicBuilding #Codegnan #Mentorship

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories