Today I realized why we should avoid using result+= c in Java. 👉 Every time we use + with String, a new object is created (because Strings are immutable). 👉 This leads to O(n²) time complexity in loops and impacts performance. Instead, we should use StringBuilder / StringBuffer for efficient string manipulation. Here are 🔟 practical string optimization techniques I noted: 🥇 1. Use StringBuilder instead of + ❌ Bad String result = ""; for(char c : arr){ result += c; } ✅ Good StringBuilder sb = new StringBuilder(); for(char c : arr){ sb.append(c); } return sb.toString(); 👉 Reason: Avoids creating new objects repeatedly 🥈 2. Use charAt() instead of toCharArray() (when possible) ❌ char[] arr = str.toCharArray(); ✅ for(int i = 0; i < str.length(); i++){ char c = str.charAt(i); } 👉 Saves extra memory 🥉 3. Use StringBuilder.reverse() ❌ Manual reverse ✅ new StringBuilder(str).reverse().toString(); 🏅 4. Use String.join() String res = String.join(",", a, b, c); 🎯 5. Use .equals() instead of == str1.equals(str2); 👉 == compares reference, not value 🧠 6. Use startsWith() / endsWith() str.startsWith("abc"); ⚡ 7. Use indexOf() for search str.indexOf("abc"); 🔥 8. Avoid split() inside loops String[] parts = str.split(","); 👉 split() uses regex → expensive 🧩 9. Use StringBuilder for insert/delete StringBuilder sb = new StringBuilder(str); sb.insert(i, "x"); 🚀 10. Use String.valueOf() String s = String.valueOf(num); 💡 Key takeaway: If you’re working with strings in loops → always think about immutability + performance #Java #BackendDevelopment #Coding #Performance #DataStructures #SoftwareEngineering
Avoid String += in Java for Efficient String Manipulation
More Relevant Posts
-
🚀 Java Streams Practice - First Non-Repeating Character Ever come across this classic question? 👉 "Find the first non-repeating character in a string" Here’s a clean and efficient way to solve it using Java Streams 👇 String str = "swiss"; 💡 Approach Explained 1️⃣ Convert String → Stream of Characters i. str.chars() gives an IntStream .mapToObj(c -> (char) c) converts it into a Stream<Character> 2️⃣ Count Frequency (Preserving Order) i. Collectors.groupingBy(...) groups characters ii. Function.identity() -> key is the character itself iii. Collectors.counting() -> counts occurrences iv. LinkedHashMap::new -> preserves insertion order (important!) 👉 Why LinkedHashMap? Because we need the first non-repeating character in the original order. 3️⃣ Filter First Non-Repeating Character i. entrySet().stream() -> iterate over map entries ii. .filter(e -> e.getValue() == 1) -> only unique characters iii. .map(Map.Entry::getKey) -> extract character iv. .findFirst() -> get first match 🧠 Pro Tip If you use HashMap instead of LinkedHashMap, you might get the wrong answer because order is not guaranteed. 💬 Have you solved this problem differently? Drop your approach in the comments! 💻 I’ve added my Java solution in the comments below. Please let me know if there are any other approaches I could try. #Java #Java8 #JavaStreams #CodingInterview #DSA #FunctionalProgramming #Developers #BackendDevelopment
To view or add a comment, sign in
-
-
Ever wondered why we need a "StringBuilder" in Java when we already have "String"? 🤔 At first glance, "String" seems perfectly fine for handling text. But the real difference shows up when we start modifying or concatenating strings multiple times. 👉 The key point: Strings in Java are immutable. This means every time you concatenate a string, a new object is created in memory. Example: String str = "Hello"; str = str + " World"; str = str + "!"; Behind the scenes, this creates multiple objects: - "Hello" - "Hello World" - "Hello World!" This repeated object creation increases memory usage and puts extra load on the Garbage Collector (GC). 🚨 In scenarios like loops or heavy string manipulation, this can significantly impact performance. So where does "StringBuilder" help? "StringBuilder" is mutable, meaning it modifies the same object instead of creating new ones. StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); sb.append("!"); ✅ Only one object is used and updated internally ✅ Faster performance ✅ Less memory overhead ✅ Reduced GC pressure When should you use it? ✔ When performing frequent string modifications ✔ Inside loops ✔ When building dynamic strings (logs, queries, JSON, etc.) 💡 Quick takeaway: - Use "String" for simple, fixed text - Use "StringBuilder" for dynamic or repeated modifications 💥 Advanced Tip: StringBuilder Capacity vs Length Most developers know StringBuilder is faster—but here’s something interviewers love 👇 👉 length() = actual number of characters 👉 capacity() = total allocated memory By default, capacity starts at 16 and grows dynamically when needed: ➡️ New capacity = (old * 2) + 2 💡 Why it matters? Frequent resizing creates new internal arrays and copies data → impacts performance. ✅ Pro tip: When working with loops or large data, initialize capacity in advance: StringBuilder sb = new StringBuilder(1000); Understanding this small concept can make a big difference in writing efficient Java code 🚀 #Java #Programming #Performance #CodingTips #Developers
To view or add a comment, sign in
-
-
Leetcode Practice - 8. String to Integer (atoi) The problem is solved using JAVA. Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: ✔ Whitespace: Ignore any leading whitespace (" "). ✔ Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present. ✔ Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. ✔ Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1. Return the integer as the final result. Example 1: Input: s = "42" Output: 42 Explanation: The underlined characters are what is read in and the caret is the current reader position. Step 1: "42" (no characters read because there is no leading whitespace) ^ Step 2: "42" (no characters read because there is neither a '-' nor '+') ^ Step 3: "42" ("42" is read in) #LeetCode #Java #StringHandling #CodingPractice #ProblemSolving #DSA #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
I used to think String comparison in Java was broken. Turns out I just didn't understand memory. Here's what clicked once I learned how the String Pool, Heap, and Stack actually work together: 𝟭. == on Strings lies to you. "hello" == "hello" → true (same pool reference) new String("hello") == new String("hello") → false (different heap objects) Use .equals(). No exceptions. 𝟮. String literals are shared. new String() is not. Java reuses string literals from the pool to save memory. The moment you write new String("..."), you're opting out of that and creating a fresh heap object for no reason. 𝟯. Concatenation in a loop is a heap bomb. Each + creates a new String object. 1000 iterations = 1000 objects. Use StringBuilder — it mutates in place. 𝟰. Stack is fast but tiny. Heap is large but needs GC. Local variables and method calls live on the stack — gone the moment the method returns. Objects (including all Strings) live on the heap until the GC cleans them up. 𝟱. The String Pool moved to the Heap in Java 7. Before that it lived in PermGen — a fixed space that caused OutOfMemoryErrors on apps with lots of string-heavy operations. Now it's heap-managed and much safer. 𝟲. intern() exists but use it carefully. It forces a string onto the pool for reuse. Great for memory when you have thousands of identical strings — but overdo it and you just trade one memory problem for another. Once you see strings as objects with addresses, not just values, a lot of Java behaviour suddenly makes sense. What Java memory concept confused you the most starting out? 👇 #Java #JVM #MemoryManagement #StringPool #SoftwareEngineering
To view or add a comment, sign in
-
🔥 Day 14: Immutable Class (How String is Immutable in Java) One of the most important concepts in Java — especially for interviews 👇 🔹 What is an Immutable Class? 👉 Definition: An immutable class is a class whose objects cannot be changed once created. 🔹 Example: String String s = "Hello"; s.concat(" World"); System.out.println(s); // Hello (not changed) 👉 Why Because String is immutable 🔹 How String Becomes Immutable? ✔ String class is final (cannot be extended) ✔ Internal data is private & final ✔ No methods modify the original object ✔ Any change creates a new object 🔹 Behind the Scenes String s1 = "Hello"; String s2 = s1.concat(" World"); System.out.println(s1); // Hello System.out.println(s2); // Hello World 👉 s1 remains unchanged 👉 s2 is a new object 🔹 Why Immutability is Important? ✔ Thread-safe (no synchronization needed) ✔ Security (safe for sharing data) ✔ Caching (String Pool optimization) ✔ Reliable & predictable behavior 🔹 How to Create Your Own Immutable Class? ✔ Make class final ✔ Make fields private final ✔ No setters ✔ Initialize via constructor only ✔ Return copies of mutable objects 🔹 Real-Life Analogy 📦 Like a sealed box — once created, you cannot change what’s inside. 💡 Pro Tip: Use immutable objects for better performance and safety in multi-threaded applications. 📌 Final Thought: "Immutability = Safety + Simplicity + Performance" #Java #Immutable #String #Programming #JavaDeveloper #Coding #InterviewPrep #Day14
To view or add a comment, sign in
-
-
. 🚀 Day 2 — First & Last Index of Repeating Characters ✅ Problem Find the first and last occurrence index of each repeating character in a string. import java.util.*; import java.util.stream.*; class FirstLastIndexFinder { public static void main(String[] args) { String input = "Programming"; Map<Character, List<Integer>> map = IntStream.range(0, input.length()) .boxed() .collect(Collectors.groupingBy( i -> input.charAt(i), LinkedHashMap::new, Collectors.toList() )); map.entrySet().stream() .filter(entry -> entry.getValue().size() > 1) .forEach(entry -> { List<Integer> indexes = entry.getValue(); System.out.println( "Key: " + entry.getKey() + ", First Index: " + indexes.get(0) + ", Last Index: " + indexes.get(indexes.size() - 1) ); }); } } 💡 Explanation 👉 Step-by-step: Use IntStream.range() to iterate over indexes Group indexes by character using groupingBy() Use LinkedHashMap to maintain insertion order Filter characters that appear more than once Get: First index → indexes.get(0) Last index → indexes.get(size - 1) ✅ Output Key: r, First Index: 1, Last Index: 9 Key: g, First Index: 3, Last Index: 10 Key: m, First Index: 6, Last Index: 7 Happy Learning!!!
To view or add a comment, sign in
-
Two ways to create a String in Java. One is always wrong for 99% of use cases. Most senior devs still get asked this. 👇 String a = "hello"; // ✅ String literal String b = new String("hello"); // ❌ Almost always wrong Both hold "hello". But they are NOT the same in memory. Here's what actually happens: → "hello" (literal) → goes to String Pool → reused if same value exists → new String("hello") → always creates a NEW object on the Heap → Pool bypassed → no reuse → wasteful memory allocation → == comparison breaks completely with new String() The comparison trap: String a = "hello"; String b = "hello"; System.out.println(a == b); // true (same pool reference) String c = new String("hello"); String d = new String("hello"); System.out.println(c == d); // false (different heap objects) So when is new String() EVER valid? Rare case: when you intentionally need a separate object with its own identity. Example: password char-to-String conversion before zeroing out the original. In 7 years of fintech — I've used it maybe twice. The rule is simple: → Always use String literals → Never use new String() unless you have a very specific reason → Always compare with .equals(), never == Save this — your next Java interview will thank you. 🔖 Have you ever been caught off guard by new String() behavior? Drop it below 👇 #Java #CoreJava #JavaDeveloper #BackendEngineering #SeniorEngineer 🥰
To view or add a comment, sign in
-
Day 12 Today’s Java practice was about solving the Leader Element problem. Instead of using nested loops, I used a single traversal from right to left, which made the solution clean and efficient. A leader element is one that is greater than all the elements to its right. Example: Input: {16,17,5,3,4,2} Leaders: 17, 5, 4, 2 🧠 Approach I used: ->Start traversing from the rightmost element ->Keep track of the maximum element seen so far ->If the current element is greater than the maximum, it becomes a leader ->This is an efficient approach with O(n) time complexity and no extra space. ================================================= // Online Java Compiler // Use this editor to write, compile and run your Java code online class Main { public static void main(String[] args) { int a [] ={16,17,5,3,4,2}; int length=a.length; int maxRight=a[length-1]; System.out.print("Leader elements are :"+maxRight+" "); for(int i=a[length-2];i>=0;i--) { if(a[i]>maxRight) { maxRight=a[i]; System.out.print(maxRight+" "); } } } } Output:Leader elements are :2 4 5 17 #AutomationTestEngineer #Selenium #Java #DeveloperJourney #Arrays
To view or add a comment, sign in
-
-
🚀 ArrayDeque in Java 📌 How to use ArrayDeque ad = new ArrayDeque(); ad.add(10); ad.add(20); ad.add(30); System.out.println(ad); 📌 Points to Remember 1️⃣ Initial capacity = 16 2️⃣ Heterogeneous data → Yes, it will store 3️⃣ Preserves order of insertion 4️⃣ Duplicates are allowed 5️⃣ Null values are NOT allowed 📌 Constructors (3) 1. ArrayDeque() 2. ArrayDeque(int) 3. ArrayDeque(Collection) Example: LinkedList ll = new LinkedList(); ll.add(10); ll.add(20); ArrayDeque ad = new ArrayDeque(ll); 📌 Internal Structure 👉 Resizable array (Dynamic array) 📌 Hierarchy Iterable → Collection → Queue → Deque → ArrayDeque 📌 Accessing Elements ❌ No indexes in ArrayDeque ❌ Normal for loop will not work ✔️ Use for-each loop for(Object a : ad){ System.out.println(a); } 📌 Iterator (Forward) Iterator cursor = ad.iterator(); while(cursor.hasNext()){ System.out.println(cursor.next()); } 📌 Descending Iterator (Backward) Iterator cursor = ad.descendingIterator(); while(cursor.hasNext()){ System.out.println(cursor.next()); } 📌 When to use ArrayDeque ✔️ Heterogeneous data ✔️ Duplicate entries ✔️ No null values ✔️ Preserves order of insertion 🎯 Summary: ArrayDeque is a resizable array-based data structure that allows insertion and deletion from both ends, preserves order, allows duplicates, but does not allow null values and indexing. #Java #ArrayDeque #JavaCollections #Programming #Coding #Developers #Learning
To view or add a comment, sign in
-
💻 String vs StringBuffer vs StringBuilder in Java – Know the Difference! In Java, handling text data is very common. Let’s understand the three important classes: 🔹 1. String ✔ Immutable (cannot be changed once created) ✔ Any modification creates a new object ✔ Safe and widely used Example: "String s = "Hello";" "s = s + " World"; // creates new object" --- 🔹 2. StringBuffer ✔ Mutable (can be changed) ✔ Thread-safe (synchronized) ✔ Slightly slower due to synchronization Example: "StringBuffer sb = new StringBuffer("Hello");" "sb.append(" World");" --- 🔹 3. StringBuilder ✔ Mutable (can be changed) ✔ Not thread-safe ✔ Faster than StringBuffer Example: "StringBuilder sb = new StringBuilder("Hello");" "sb.append(" World");" --- 💡 Key Difference: String = Immutable StringBuffer = Mutable + Thread-safe StringBuilder = Mutable + Faster 🚀 Use String for simple tasks, StringBuffer for multi-threading, and StringBuilder for better performance in single-threaded applications. #FortuneCloudTechnology #Java #Programming #String #JavaBasics #Coding #Developers #Learning
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