String vs StringBuilder vs StringBuffer in Java

🔥 𝐒𝐭𝐫𝐢𝐧𝐠 𝐯𝐬 𝐒𝐭𝐫𝐢𝐧𝐠𝐁𝐮𝐢𝐥𝐝𝐞𝐫 𝐯𝐬 𝐒𝐭𝐫𝐢𝐧𝐠𝐁𝐮𝐟𝐟𝐞𝐫 𝐢𝐧 𝐉𝐚𝐯𝐚 — 𝐒𝐭𝐨𝐩 𝐂𝐨𝐧𝐟𝐮𝐬𝐢𝐧𝐠 𝐓𝐡𝐞𝐦! This is one of the most asked Java interview questions — yet most developers can't explain the difference clearly. Let me fix that 👇 🔵 𝐒𝐭𝐫𝐢𝐧𝐠 — 𝐈𝐦𝐦𝐮𝐭𝐚𝐛𝐥𝐞 & 𝐓𝐡𝐫𝐞𝐚𝐝-𝐒𝐚𝐟𝐞 𝐒𝐭𝐫𝐢𝐧𝐠 𝐬𝟏 = "𝐇𝐞𝐥𝐥𝐨"; 𝐒𝐭𝐫𝐢𝐧𝐠 𝐬𝟐 = 𝐬𝟏 + " 𝐖𝐨𝐫𝐥𝐝"; // creates a NEW object every time! 𝐒𝐭𝐫𝐢𝐧𝐠 𝐬𝟑 = "𝐇𝐞𝐥𝐥𝐨"; // s1 == s3 → true (same String pool reference) // s1 == s2 → false (s2 is a brand new object) ✅ Stored in String Pool — memory efficient for reuse ✅ Thread-safe by design (immutable) ❌ Every + or concat() creates a new object — bad in loops! 🩷 𝐒𝐭𝐫𝐢𝐧𝐠𝐁𝐮𝐢𝐥𝐝𝐞𝐫 — 𝐌𝐮𝐭𝐚𝐛𝐥𝐞 & 𝐅𝐚𝐬𝐭 𝐒𝐭𝐫𝐢𝐧𝐠𝐁𝐮𝐢𝐥𝐝𝐞𝐫 𝐬𝐛 = 𝐧𝐞𝐰 𝐒𝐭𝐫𝐢𝐧𝐠𝐁𝐮𝐢𝐥𝐝𝐞𝐫(); 𝐬𝐛.𝐚𝐩𝐩𝐞𝐧𝐝("𝐇𝐞𝐥𝐥𝐨").𝐚𝐩𝐩𝐞𝐧𝐝(" 𝐖𝐨𝐫𝐥𝐝"); // same object 𝐬𝐛.𝐢𝐧𝐬𝐞𝐫𝐭(𝟎, "𝐒𝐚𝐲: "); 𝐬𝐛.𝐫𝐞𝐯𝐞𝐫𝐬𝐞(); 𝐒𝐭𝐫𝐢𝐧𝐠 𝐫𝐞𝐬𝐮𝐥𝐭 = 𝐬𝐛.𝐭𝐨𝐒𝐭𝐫𝐢𝐧𝐠(); ✅ Modifies the same object — no new allocations ✅ Fastest option for string manipulation ❌ NOT thread-safe — don't share between threads 🟣 𝐒𝐭𝐫𝐢𝐧𝐠𝐁𝐮𝐟𝐟𝐞𝐫 — 𝐓𝐡𝐫𝐞𝐚𝐝-𝐒𝐚𝐟𝐞 𝐛𝐮𝐭 𝐒𝐥𝐨𝐰𝐞𝐫 𝐒𝐭𝐫𝐢𝐧𝐠𝐁𝐮𝐟𝐟𝐞𝐫 𝐬𝐛 = 𝐧𝐞𝐰 𝐒𝐭𝐫𝐢𝐧𝐠𝐁𝐮𝐟𝐟𝐞𝐫(); 𝐬𝐛.𝐚𝐩𝐩𝐞𝐧𝐝("𝐇𝐞𝐥𝐥𝐨"); // synchronized  𝐬𝐛.𝐚𝐩𝐩𝐞𝐧𝐝(" 𝐖𝐨𝐫𝐥𝐝"); // Same API as StringBuilder, but all methods are synchronized ✅ Thread-safe — safe for multi-threaded access ❌ Synchronization adds overhead — slower than StringBuilder 📊 𝐐𝐮𝐢𝐜𝐤 𝐂𝐨𝐦𝐩𝐚𝐫𝐢𝐬𝐨𝐧 𝐅𝐞𝐚𝐭𝐮𝐫𝐞 𝐒𝐭𝐫𝐢𝐧𝐠 𝐒𝐭𝐫𝐢𝐧𝐠𝐁𝐮𝐢𝐥𝐝𝐞𝐫 𝐒𝐭𝐫𝐢𝐧𝐠𝐁𝐮𝐟𝐟𝐞𝐫 Mutable? ❌ No ✅ Yes ✅ Yes Thread-safe? ✅ Yes ❌ No ✅ Yes Speed Slowest* Fastest Moderate Use case Constants Loops Multi-thread *+ in a loop is slow. Compiler may optimize single-line concatenation. 💡 Golden Rule: Use 𝐒𝐭𝐫𝐢𝐧𝐠 for fixed values. Use 𝐒𝐭𝐫𝐢𝐧𝐠𝐁𝐮𝐢𝐥𝐝𝐞𝐫 for manipulation in single-threaded code. Use 𝐒𝐭𝐫𝐢𝐧𝐠𝐁𝐮𝐟𝐟𝐞𝐫 only when multiple threads share the same buffer. Drop a 🔥 if this cleared your confusion! Tag a Java dev who still uses + inside loops 😄 👇 Which one do you use most in your projects? #Java #String #StringBuilder #StringBuffer #CoreJava #Backend #SpringBoot #JavaDeveloper #100DaysOfCode #InterviewPrep #Programming

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories