StringBuffer
StringBuffer works almost identically to StringBuilder — it's mutable and used for building or modifying text. The key difference is that StringBuffer is thread-safe, meaning it's designed to be used safely when multiple threads access it a…
1. What is StringBuffer?
StringBuffer works almost identically to StringBuilder — it's mutable and used for building or modifying text. The key difference is that StringBuffer is thread-safe, meaning it's designed to be used safely when multiple threads access it at the same time.
2. Why is it used?
In programs where multiple parts of the code (running as separate threads) might modify the same text data at the same time, StringBuffer protects against data corruption, unlike StringBuilder.
3. Real-Life Example
Think of a shared notice board in an office, where a security guard makes sure only one person edits it at a time so nothing gets messed up. StringBuffer behaves like this careful, one-at-a-time editing process.
4. Syntax
javaStringBuffer sb = new StringBuffer(); sb.append("text"); sb.insert(position, "text"); sb.reverse();
5. Example Program
javapublic class StringBufferDemo { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello"); sb.append(" World"); System.out.println(sb); } }
Output:
Hello World6. Key Points to Remember
StringBuffermethods are synchronized (thread-safe);StringBuildermethods are not.- Because of this safety check,
StringBufferis slightly slower thanStringBuilderin single-threaded programs. - Use
StringBuilderfor regular, single-threaded work, andStringBufferonly when multiple threads need safe access — this distinction is a common interview question.