Java Mutable Strings: StringBuffer, StringBuilder & StringTokenizer

DAY 17: CORE JAVA TAP Academy 🚀 Understanding Mutable Strings in Java – StringBuffer, StringBuilder & StringTokenizer In Java, String objects are immutable. That means once a string is created, it cannot be changed. Every modification creates a new object in memory. But what if we need frequent modifications? 🤔 That’s where mutable strings come into play! 🔹 1️⃣ StringBuffer StringBuffer is a mutable, thread-safe class used to modify strings dynamically. ✅ Key Features: Thread-safe (synchronized) Slower than StringBuilder (due to synchronization) Ideal for multi-threaded environments 📌 Important Methods: append() → Adds data to the existing string capacity() → Returns current buffer capacity trimToSize() → Reduces capacity to match current string length 💻 Example: StringBuffer sb = new StringBuffer("Hello"); System.out.println("Capacity: " + sb.capacity()); // Default 16 + length sb.append(" World"); sb.trimToSize(); System.out.println("Updated Capacity: " + sb.capacity()); 🔹 2️⃣ StringBuilder StringBuilder is also mutable but not thread-safe. ✅ Key Features: Faster than StringBuffer Best for single-threaded applications Preferred in most cases 📌 Important Methods: append() capacity() trimToSize() 💻 Example: StringBuilder sb = new StringBuilder("Java"); System.out.println("Capacity: " + sb.capacity()); sb.append(" Programming"); sb.trimToSize(); System.out.println("Updated Capacity: " + sb.capacity()); 🔹 3️⃣ StringTokenizer StringTokenizer is used to break a string into tokens based on delimiters. 📌 Example: String str = "Java,Python,C++"; StringTokenizer st = new StringTokenizer(str, ","); while(st.hasMoreTokens()) { System.out.println(st.nextToken()); } ⚠ Note: StringTokenizer is considered a legacy class. Modern alternatives include: String.split() Pattern and Matcher classes 🎯 Quick Comparison Feature StringBuffer StringBuilder Mutable ✅ ✅ Thread-Safe ✅ ❌ Performance Slower Faster Recom mended Multi- Single- threaded threaded --- 💡 Key Takeaway: Use StringBuilder for better performance in most applications. Use StringBuffer when thread safety is required. Avoid StringTokenizer in modern development; prefer split() or regex. #Java #JavaProgramming #CoreJava #StringHandling #Programming #Developers

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories