Commit b08c255
committed
feat: demonstrate immutability of String vs mutability of StringBuffer and StringBuilder
WHAT was added:
- Implemented `StringBufferBuilder` to compare `String`, `StringBuffer`, and `StringBuilder`.
- Showed how `concat()` on `String` creates a new object (ignored in this case).
- Demonstrated `append()` on `StringBuffer` and `StringBuilder`, which directly modify the same object.
WHY this matters:
- Highlights the **core difference**:
- `String` → immutable (operations create new objects).
- `StringBuffer` → mutable + thread-safe (synchronized).
- `StringBuilder` → mutable + faster (non-synchronized).
- Helps choose the right class depending on **immutability, performance, and concurrency needs**.
PROGRAM OUTPUT:
- String → `Hello` (unchanged, since concat() result was not stored).
- StringBuffer → `Hello World` (append modifies original).
- StringBuilder → `Hello World` (append modifies original).
REAL-WORLD APPLICATIONS:
- **String** → Constants, configuration values, keys where immutability ensures safety.
- **StringBuilder** → Efficient text manipulation in single-threaded apps (e.g., report generation, JSON building).
- **StringBuffer** → Safe for concurrent modifications in multi-threaded contexts (e.g., shared logging systems).
KEY TAKEAWAYS:
1. `String` is immutable → safe but slower for repeated modifications.
2. `StringBuffer` is mutable & synchronized → safer in multi-threaded use.
3. `StringBuilder` is mutable & non-synchronized → fastest in single-threaded use.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent fe415c0 commit b08c255
1 file changed
+28
-7
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | 3 | | |
| 4 | + | |
5 | 5 | | |
6 | | - | |
7 | 6 | | |
8 | 7 | | |
9 | 8 | | |
10 | | - | |
11 | 9 | | |
12 | | - | |
13 | 10 | | |
14 | 11 | | |
15 | 12 | | |
16 | | - | |
17 | 13 | | |
18 | | - | |
19 | 14 | | |
20 | 15 | | |
21 | | - | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
0 commit comments