Q 30 - Strings #33
Answered
by
HARSHITH-MV
AmjustGettingStarted
asked this question in
Q&A
-
Dif btw String, String Builder & String Buffer? |
Beta Was this translation helpful? Give feedback.
Answered by
HARSHITH-MV
Jul 18, 2025
Replies: 1 comment
-
✅ Difference Between
|
Feature | String | StringBuilder | StringBuffer |
---|---|---|---|
Mutability | Immutable – cannot be changed | Mutable – can be changed | Mutable – can be changed |
Thread Safety | Not thread-safe | Not thread-safe | Thread-safe (synchronized methods) |
Performance | Slow for modifications | Faster than StringBuffer | Slower than StringBuilder |
Synchronization | No | No | Yes |
Use Case | Use when string doesn’t change | Use in single-threaded environments | Use in multi-threaded environments |
Package | java.lang.String | java.lang.StringBuilder | java.lang.StringBuffer |
Introduced In | Java 1.0 | Java 1.5 | Java 1.0 |
🧠 Example:
➤ String
(Immutable)
String s = "Hello";
s.concat(" World");
System.out.println(s); // Output: Hello
The original
s
is unchanged. A new string is created, but not stored.
➤ StringBuilder
(Mutable & Fast, Not Thread-Safe)
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
Efficient for string operations in single-threaded environments.
➤ StringBuffer
(Mutable & Thread-Safe)
StringBuffer sbf = new StringBuffer("Hello");
sbf.append(" World");
System.out.println(sbf); // Output: Hello World
Use this in multi-threaded environments to avoid concurrency issues.
🔁 Summary
When to Use |
---|
Use String when the string is fixed or changed rarely. |
Use StringBuilder for fast string manipulation in single-threaded code. |
Use StringBuffer when multiple threads modify the string and thread safety is required. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
AmjustGettingStarted
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
✅ Difference Between
String
,StringBuilder
, andStringBuffer
in Java🧠 Example:
➤
String
(Immutable)