← Back to libraryQuestion 50 of 273
JavaBeginner

StringBuilder vs StringBuffer

📖 Detailed Explanation:

Both StringBuilder and StringBuffer are mutable string builders. StringBuffer is synchronized (thread-safe but slow). StringBuilder is non-synchronized (fast but not thread-safe). Use StringBuilder in single-threaded contexts for performance. Use StringBuffer only in legacy multithreaded code.

🌍 Real-World Example:

StringBuffer: A shared notebook with locks (only one person writes at a time). StringBuilder: A personal notebook (only you write).

🎯 Scenario-Based Interview Question:

When would you use StringBuffer over StringBuilder in modern Java?