🔡 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
How to Combine Two Strings Character by Character in Java
More Relevant Posts
-
🚀 Day 15 of 30 Days Java Challenge — StringBuilder vs StringBuffer in Java 💡 🔹 What’s the problem with normal Strings? In Java, Strings are immutable — that means once created, their value cannot be changed. Whenever you modify a string (like concatenating or replacing text), Java actually creates a new String object, which can be inefficient when you do it many times. 📘 Example: String name = "John"; name = name + " Doe"; Here, Java creates two String objects: "John" "John Doe" If you do this in a loop, it wastes both memory and time. 🔹 Enter StringBuilder and StringBuffer Both are mutable classes — meaning you can change the content without creating new objects. Feature StringBuilder StringBuffer Mutability ✅ Mutable ✅ Mutable Thread-safe ❌ No ✅ Yes Performance 🚀 Faster 🐢 Slightly slower Use case Single-threaded code Multi-threaded code 💡 Real-world Example Imagine you’re building an app that generates usernames for a list of users. Using StringBuilder: public class UsernameGenerator { public static void main(String[] args) { String[] names = {"Alice", "Bob", "Charlie"}; StringBuilder sb = new StringBuilder(); for (String name : names) { sb.append("user_").append(name.toLowerCase()).append(" "); } System.out.println(sb.toString()); } } ✅ Output: user_alice user_bob user_charlie Here, we only used one StringBuilder object to build the final string efficiently — no extra objects were created in the process. 💡 Thread-safe Example (StringBuffer) If multiple threads are updating the same string, use StringBuffer to avoid data corruption. StringBuffer sb = new StringBuffer(); sb.append("Processing "); sb.append("data..."); System.out.println(sb); 🎯 Key Takeaways Use StringBuilder → when working in a single-threaded environment (most common). Use StringBuffer → when working in multi-threaded environments. Both are more efficient than using normal String for repeated concatenations. 🧩 Real-life Analogy Think of String as a sealed envelope — if you want to change the message, you must write a new letter. But StringBuilder is like a whiteboard — you can erase and rewrite easily! 💬 What’s your pick? Do you mostly use StringBuilder or StringBuffer in your code? Share your thoughts below 👇 #Java #CodingChallenge #LearningJourney #StringBuilder #StringBuffer #JavaBeginners
To view or add a comment, sign in
-
-
🚀 Today I Deepened My Understanding of Strings in Java Today, I explored the differences between String, StringBuffer, and StringBuilder classes in Java — focusing on mutability, performance, and thread safety. 🔹 1️⃣ String (Immutable) Strings in Java are immutable — once created, they cannot be modified. Every modification creates a new String object. Thread-safe: Yes (due to immutability) Performance: Slower for frequent modifications Common Methods: length(), charAt(), substring(), toUpperCase(), toLowerCase(), equals(), equalsIgnoreCase(), indexOf(), startsWith(), endsWith(), replace(), split() 🔹 2️⃣ StringBuffer (Mutable & Thread-Safe) Used when frequent string modifications are required. Mutable: Can be modified without creating new objects. Thread-safe: Yes (methods are synchronized) Performance: Slower compared to StringBuilder due to synchronization overhead. Common Methods: append(), insert(), replace(), delete(), reverse(), capacity(), ensureCapacity(), setCharAt() 🔹 3️⃣ StringBuilder (Mutable & Non-Thread-Safe) Similar to StringBuffer, but not synchronized, hence faster. Thread-safe: No Best for: Single-threaded environments. Performance: Faster than StringBuffer Methods: Same as StringBuffer 🔹 4️⃣ Conversion Between Types Immutable → Mutable: StringBuffer sb = new StringBuffer(str); StringBuilder sbl = new StringBuilder(str); Mutable → Immutable: String str = sb.toString(); 🔹 5️⃣ String Tokenization I also explored string splitting techniques in Java: split() Method: Modern and efficient; uses regex. StringTokenizer Class: Older and slower; uses more memory. Example: String s = "Java is powerful"; String[] parts = s.split(" "); // Preferred modern approach import java.util.StringTokenizer; // StringTokenizer StringTokenizer st = new StringTokenizer("Java is powerful"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } 💡 Final Insight Understanding how Java handles string operations — from immutability to synchronization — is crucial for writing efficient and thread-safe code. #Java #LearningJourney #SoftwareDevelopment #StringHandling #CodingInJava #JavaDeveloper
To view or add a comment, sign in
-
-
🚀 Arrays, Loops, or Streams: Which One Is Faster in Java? When working with Java, one question appears again and again: “What’s faster for iterating and processing data: arrays, traditional loops, or streams?” Here’s the straight answer: 👉 Arrays with a traditional for loop are almost always the fastest. 👉 Streams are slower, but offer readability and easy parallelization. Let’s break it down. 🧠 1. Arrays — The Fastest Option Arrays are the simplest and most direct structure in the JVM. They live in a continuous block of memory and allow direct index access. ✔ Why are arrays faster? ✅Direct access via array[i] ✅Zero iterator or object overhead ✅No boxing/unboxing ✅Excellent CPU cache locality Best for: 🟢 High-performance scenarios 🟢Large datasets 🟢Fixed-size collections 🔁 2. Traditional Loops — The Best Balance Using for or enhanced for on an ArrayList is extremely fast and predictable. The JVM heavily optimizes these loops during JIT compilation. ✔ Why are loops fast? ✅ Minimal overhead ✅No extra object allocation ✅Very friendly to JVM optimizations Best for: 🟢Most general Java applications 🟢Dynamic-sized collections 🟢Scenarios needing both speed and readability 🌊 3. Streams — Modern, Clean, but Not Always Fast Streams bring functional style, expressiveness, and powerful transformations. But they pay for it with overhead. ✔ Why are streams slower? 📛 Create internal objects (Stream, lambdas, iterators) 📛Pipeline stages add layers of abstraction 📛Can trigger boxing/unboxing (e.g., Stream<Integer>) ✔ When streams shine 🟢Complex transformations 🟢Data filtering and mapping 🟢Readable, declarative code 🟢Easy parallelization with .parallel() ⚠ When to avoid streams 📛Hot code paths 📛Low-level performance-critical loops 📛Very small operations where abstraction cost dominates 🥇 So… Which One Is Actually Faster? StructurePerformanceBest Use CaseArray + for loop 🥇 FastestHigh-performance, fixed-size structuresArrayList + for loop 🥈 Very fastGeneral-purpose programmingStreams 🥉 SlowerReadability & functional transformationsParallel Streams⚡ 🏆 Fast for large workloadsCPU-heavy, large datasets 📌 Final Conclusion If performance is your priority: 👉 Use arrays with traditional loops. If you want clean, expressive code: 👉 Use streams. If you’re processing large CPU-intensive workloads: 👉 Consider parallelStream() — it may outperform everything else. 🔖 #Java #SpringBoot #Array #BackendDevelopment #SoftwareEngineering #APIDevelopment #JavaDeveloper #BackendEngineer
To view or add a comment, sign in
-
-
𝗜𝗻𝘁𝗲𝗿𝗻𝗮𝗹 𝗪𝗼𝗿𝗸𝗶𝗻𝗴 𝗼𝗳 𝘁𝗵𝗲 𝗦𝘁𝗿𝗶𝗻𝗴 𝗣𝗼𝗼𝗹 𝗶𝗻 𝗝𝗮𝘃𝗮. This is a very common Java interview question, and many people still get confused about how the String Pool really works. Here’s the simple and correct explanation 👇 --- 1. String Pool is inside the heap memory In modern Java versions (Java 7+), the String Pool is a special managed area inside the heap, not outside. When you write: String s1 = "Java"; Java stores "Java" in the String Pool (if not already stored). --- 2. String literals always go to the pool String s1 = "Hello"; String s2 = "Hello"; Here, both s1 and s2 point to the same object in the pool. This saves memory and avoids duplicates. --- 3. new String("Java") creates a new heap object String s = new String("Java"); This always creates a new object in heap, even if "Java" already exists in the pool. But note: If the literal "Java" was not already in the pool, the JVM will first add the literal into the pool during class loading — not because of the new keyword. So final behavior: Literal "Java" → in pool New String object → in heap --- 4. intern() returns the pool version String s1 = new String("Java").intern(); String s2 = "Java"; Now both point to the same pool object. intern() simply returns the pooled instance. --- 5. Why String Pool exists? Because strings are used everywhere, and many repeat. The pool: Reduces memory usage Reuses common strings Improves performance --- 6. == vs equals() (Most asked in interviews) String a = "Hi"; String b = "Hi"; a == b; // true → same pool object But: String x = new String("Hi"); x == b; // false → heap object vs pool object == → checks reference (same object?) equals() → checks value (same text?) --- 💡 In short String Pool is inside heap String literals always go to the pool new String("Java") always creates a new heap object Literal is still stored in the pool by JVM (during class loading) intern() returns the pool version == compares references, equals() compares content This topic is simple but extremely important for both interviews and performance. #Java #StringPool #JavaInternals #InterviewPrep #BackendDevelopment #CodingConcepts #CleanCode #techieanky #javainterview #Stringpool #grow #linkedin
To view or add a comment, sign in
-
💡 Part 2 — String Comparison, Concatenation & Immutability in Java In the previous post, we discussed how Strings, SCP, and intern() work in Java. Now let’s explore how they behave when we compare or modify them 👇 🔹 1️⃣ == vs .equals() String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); // true ✅ System.out.println(s1.equals(s2)); // true ✅ 👉 == → compares references (memory addresses) 👉 .equals() → compares values (content) If both strings come from the String Constant Pool (SCP), == can return true. But when we create new objects using new, they live in heap, so: String s1 = new String("Java"); String s2 = "Java"; System.out.println(s1 == s2); // false ❌ (different memory) 🔹 2️⃣ Compile-time vs Runtime Concatenation String s1 = "Ja" + "va"; String s2 = "Java"; System.out.println(s1 == s2); // true ✅ 👉 Concatenation of string literals happens at compile-time, so both refer to the same object in SCP. But when concatenation happens at runtime, a new object is created: String part = "Ja"; String s3 = part + "va"; System.out.println(s2 == s3); // false ❌ 🔹 3️⃣ Immutability of Strings String s = "abc"; s.concat("xyz"); System.out.println(s); // abc ❌ (unchanged) Strings are immutable — every modification creates a new object. To reflect the change, you must reassign: s = s.concat("xyz"); System.out.println(s); // abcxyz ✅ 🔹 4️⃣ Using intern() for Optimization If you want to make sure your heap string refers to SCP: String s1 = new String("Java"); String s2 = s1.intern(); System.out.println("Java" == s2); // true ✅ 👉 intern() makes your string memory-efficient and reusable. 🧠 Quick Recap ✅ == → reference check ✅ .equals() → content check ✅ Compile-time concat → stored in SCP ✅ Runtime concat → new object in heap ✅ Strings are immutable ✅ Use intern() for SCP optimization #Java #String #Coding #JavaDeveloper
To view or add a comment, sign in
-
🔹Matrix Multiplication in Java 1. What is a Matrix? A matrix is a rectangular array of numbers arranged in rows and columns. In Java, it is represented as a 2D array (int[][], double[][], etc.). Example: int[][] A = { {1, 2, 3}, {4, 5, 6} }; 2. What is Matrix Multiplication? Matrix multiplication is a mathematical operation where two matrices combine to form a new matrix. Unlike addition or subtraction (which are element-wise), multiplication follows a special rule: The number of columns in the first matrix must be equal to the number of rows in the second matrix. If: A = (m × n) B = (n × p) Then: C = A × B → Resultant matrix of (m × p) 3. Formula For any element C[i][j] in the result matrix: C[i][j]=∑k=0n−1A[i][k]∗B[k][j]C[i][j] = \sum_{k=0}^{n-1} A[i][k] * B[k][j]C[i][j]=k=0∑n−1A[i][k]∗B[k][j]That means: Each element of the result matrix is the dot product of: Row i from Matrix A Column j from Matrix B 4. Example Calculation A = [1 2 3] [4 5 6] B = [7 8] [9 10] [11 12] Result: C = [58 64] [139 154] So the innermost loop performs the core multiplication logic. 🧱 6. Memory Representation (Conceptually) Java stores a 2D array as an array of arrays. Example: int[][] A = new int[2][3]; Memory layout: A[0] → [1, 2, 3] A[1] → [4, 5, 6] Each row is stored as a separate 1D array reference. 7. Time and Space Complexity Time Complexity: O(n³) (because of three nested loops) Space Complexity: O(m×p) (size of resultant matrix) #Java #JavaFullStack #Programming #Matrix Multplication #Codegnan Anand Kumar Buddarapu Uppugundla Sairam Saketh Kallepu
To view or add a comment, sign in
-
-
Here are some fun basic Java code snippets to refresh the fundamental understanding. Guess the output! How many did you get right? 1.➡️ public class OverloadExample { public void show(Object obj) { System.out.println("Cat"); } public void show(String str) { System.out.println("Dog"); } public static void main(String[] args) { OverloadExample example = new OverloadExample(); example.show(null); } } 2.➡️ public class ConstructorTest { void ConstructorTest() { System.out.println("Hello"); } public static void main(String[] args) { ConstructorTest ct = new ConstructorTest(); } } 3.➡️ public class IncrementTest { public static void main(String[] args) { int x = 5; System.out.println(x++ + ++x); } } 4.➡️ public class LoopTest { public static void main(String[] args) { int i = 0; for(; i < 3; i++); System.out.println(i); } } 5.➡️ public class BooleanTest { public static void main(String[] args) { boolean b1 = true; boolean b2 = false; System.out.println(b1 & b2); System.out.println(b1 && b2); } } 6.➡️ class Main { public static void main(String[] args) { boolean b = false; System.out.println(b & test()); System.out.println("============================"); System.out.println(b && test()); } public static boolean test() { System.out.println("Called"); return false; } } 7.➡️ public class CastTest { public static void main(String[] args) { double d = 9.78; int i = (int) d; System.out.println(i); } } 8.➡️ public class PrePostTest { public static void main(String[] args) { int x = 2; int y = x++ * 3 + ++x; System.out.println(y); } } 9.➡️ public class CharTest { public static void main(String[] args) { char c = 'A'; c += 1; System.out.println(c); } } 10. ➡️public class LogicalTest { public static void main(String[] args) { int a = 5, b = 10; System.out.println(a < b || b++ < 15); System.out.println(b); } }
To view or add a comment, sign in
-
Java ke atomic level ke secrets! 🔥 --- Post 1: Java ka "Class Loading" ka hidden hierarchy!🤯 ```java public class ClassLoaderSecrets { public static void main(String[] args) { ClassLoader loader = String.class.getClassLoader(); System.out.println(loader); // null ✅ // Kyun? Bootstrap ClassLoader C++ mein implemented hai // Java mein uska koi object nahi hota! } } ``` ClassLoader Hierarchy: 1. Bootstrap (C++ implementation) - null dikhata hai 2. Platform (Java 9+) - jdk.internal.loader.ClassLoaders$PlatformClassLoader 3. Application - sun.misc.Launcher$AppClassLoader Secret: Bootstrap ClassLoader Java mein visible nahi hota! 💀 --- Post 2: Java ka "Lambda Metafactory" internal magic!🔥 ```java public class LambdaSecrets { public static void main(String[] args) { Runnable r = () -> System.out.println("Lambda"); // Internally ye invokeDynamic instruction banata hai // LambdaMetafactory lambda class runtime pe generate karta hai! } } ``` Bytecode Level: ``` invokedynamic #2, 0 // LambdaMetafactory.metafactory() call ``` Internal Process: 1. invokedynamic instruction 2. LambdaMetafactory call 3. Runtime pe synthetic class generation 4. Method handle return 💡 --- Post 3: Java ka "String Deduplication" G1GC feature!🚀 ```java public class StringDedup { public static void main(String[] args) { // G1GC automatically duplicate strings ko same memory point kar deta hai char[] data = {'J', 'a', 'v', 'a'}; String s1 = new String(data); String s2 = new String(data); // G1GC intern() ki tarah same char[] point kar sakta hai! } } ``` JVM Option: ``` -XX:+UseG1GC -XX:+UseStringDeduplication ``` Secret: G1GC duplicate strings ko automatically optimize karta hai! 💪 --- Post 4: Java ka "Stack Walking" internal API!🔮 ```java public class StackWalkSecrets { public static void main(String[] args) { StackWalker walker = StackWalker.getInstance(); walker.forEach(frame -> { System.out.println(frame.getClassName() + "." + frame.getMethodName()); }); } } ``` Internal Stack Frame Structure: · Method name · Class name · Line number · Bytecode index Performance: StackWalker traditionalStackTrace se 10x faster hai! 💀
To view or add a comment, sign in
-
💡Is It Possible to Overload and Override the main() Method in Java? This is one of those Java questions that seems easy at first... but actually requires some deeper thinking ....🤔 Let me explain it step by step 👇 🔸 1️⃣ Overloading the main() method ✅ Yes, this is possible! You can write multiple main() methods that have different parameters — this follows the rules of method overloading, and it works perfectly fine. public class Demo { public static void main(String[] args) { System.out.println("Main method with String[] called"); main(5); // calling the other version } public static void main(int x) { System.out.println("Overloaded main() called with int: " + x); } } 💡 The JVM will always begin running your program from the main(String[] args) method, but you can call the other overloaded main methods yourself from inside your code. So the answer is yes — overloading is allowed, but JVM only recognizes the standard form. 🔸 2️⃣ Overriding the main() method ❌ No, this cannot be done. The reason is that main() is a static method, and static methods are tied to the class itself, not to individual objects. In Java, you cannot override static methods — you can only hide them by creating one with the same name in a child class. Here's an example 👇 class Parent { public static void main(String[] args) { System.out.println("Parent main()"); } } class Child extends Parent { public static void main(String[] args) { System.out.println("Child main()"); } } Result (when you run the Child class): ➡️ Child main() This is not overriding — it's called method hiding. #OverloadingVsOverriding #MainMethodInJava #BeyondMainMethod #JavaConcepts #DecodedInJava #LogicWithJava #JavaProgramming
To view or add a comment, sign in
-
Day 04 of java fullstack development..... Hello everyone I hope you are doing well .. Today we started literals, String and String methods in java.... Literal it is a reserved word which is used for the unique representation. String it is a sequence of characters, as well as it is a literal, and string is also a class. ->.....string can be created into ways one is literal and the second one is class. String methods 1. length() 👉 returns the number of characters in string 2. chatAt() 👉 a character at specific index. 3. substring() 👉 it prints begin index and end index. 4. equals() 👉 Compare the values. 5. equalsIgnoreCase() 👉 Compares two strings ignoring case differences. 6. compareTo() 👉 Compares two strings lexicographically. Returns: 0 if equal <0 if first < second >0 if first > second 7.toLowerCase() 👉 Converts the string to all lowercase letters. 8. toUpperCase() 👉 Converts the string to all upper case 9. trim() 👉 Removes spaces from the beginning and end of the string. 10.contains(CharSequence seq) 👉 Checks if the string contains a given sequence of characters. 11.startsWith(String prefix) 👉 Checks if the string starts with the given prefix. 12. endsWith(String suffix) 👉 Checks if the string ends with the given suffix. 13. indexOf(String str) 👉 Returns the index of the first occurrence of the substring. 14. lastIndexOf(String str) 👉 Returns the index of the last occurrence of the substring. 15.replace(CharSequence old, CharSequence new) 👉 Replaces all occurrences of a substring with another. 16. isEmpty() 👉 Returns true if the string is empty (length() == 0). 17. split(String regex) 👉 Splits the string based on a delimiter and returns an array. 18. concat(String str) 👉 Joins two strings. 19. toCharArray() 👉 Converts the string into a character array. 20. valueOf() 👉 Converts non-string data types to a string. 21. matches(String regex) 👉 Checks if the string matches a regular expression pattern. etc........ #Java #PatternPrinting #CodingJourney #LearningByDoing #ProgrammingFun #FullStackDeveloper #CodeLogic
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development