1 The Problem: Why We Need Mutable Strings
Remember from our previous lessons that String is immutable. Every modification creates a new object:
- Each
+creates a new String object - The old String becomes garbage
- This is very slow and wastes memory
- With 1000 iterations: ~1000 unnecessary objects created!
The Solution: Use StringBuilder or StringBuffer - they are mutable, meaning they can be modified without creating new objects!
2 Comparison: String vs StringBuilder vs StringBuffer
- Cannot modify content
- Creates new objects
- Thread-safe (content never changes)
- Good for constants
- Content can be changed
- No new objects created
- NOT thread-safe
- Best for single-threaded
- Content can be changed
- No new objects created
- IS thread-safe
- Slightly slower (due to locking)
The only difference between StringBuilder and StringBuffer is thread safety:
- StringBuilder = Faster, but NOT safe for multiple threads
- StringBuffer = Slightly slower, but SAFE for multiple threads
3 Understanding Multi-Threading
Before we understand thread safety, let's first understand what threads are.
What is a Thread?
A thread is a lightweight process - a sequence of instructions that can run independently within a program. Think of it as a separate "worker" doing a task.
Example 1: Single-Threaded (Sequential Execution)
In a normal program, code runs sequentially - one line after another:
The output is predictable - Loop 1 finishes completely, then Loop 2 starts:
Java
Java
HTML
HTML
HTML
Example 2: Multi-Threaded (Parallel Execution)
With threads, we can run both loops at the same time:
The output is UNPREDICTABLE! Both threads run at the same time, so the output can be different each time:
HTML
Java
HTML
Java
HTML
Java
Java
HTML
HTML
Java
Java
HTML
Java
HTML
HTML
Switches between threads very fast
The CPU rapidly switches between t1 and t2, giving the illusion of parallel execution.
Note for Students:
Multi-threading is a complex topic covered in detail in:
- Concurrency courses
- Operating Systems courses
For now, just understand the basic concept: threads allow code to run simultaneously, but the order of execution is unpredictable!
4 What is Thread Safety?
When multiple threads access the same data at the same time, problems can occur if they try to modify it simultaneously.
Imagine two threads both trying to append to the same StringBuilder:
- Thread 1 wants to append "Java"
- Thread 2 wants to append "HTML"
- They both read the current state simultaneously
- They both write at the same time
- Result: Data corruption! Maybe "JaHTvMaL"
StringBuffer uses synchronization (locking):
- Thread 1 arrives, acquires the lock
- Thread 2 arrives, must wait (locked)
- Thread 1 finishes, releases the lock
- Thread 2 acquires the lock and proceeds
This ensures only one thread modifies at a time.
Thread-Safe = Safe to use with multiple threads
- StringBuffer: Thread-safe (has locking) - slightly slower
- StringBuilder: NOT thread-safe (no locking) - faster
5 Using StringBuilder
| Method | Description |
|---|---|
append(x) |
Add x to the end |
insert(pos, x) |
Insert x at position |
delete(start, end) |
Remove characters from start to end-1 |
replace(start, end, str) |
Replace range with str |
reverse() |
Reverse the content |
toString() |
Convert to String |
6 Performance Comparison: String vs StringBuilder
Let's see the dramatic difference in performance. Copy and run this code:
StringBuilder is ~1000x faster!
7 Decision Guide: Which One to Use?
Use String
- Content rarely or never changes
- Simple, short operations
- Few concatenations (1-5)
- Constants and literals
String name = "Java";
Use StringBuilder
- Content changes frequently
- Building strings in loops
- Single-threaded application
- Maximum performance needed
StringBuilder sb = ...
Use StringBuffer
- Content changes frequently
- Multiple threads access it
- Thread safety is required
- Shared mutable state
StringBuffer sbuf = ...
Simple Rule of Thumb:
- For most cases: Use
StringBuilder(99% of the time) - Only use
StringBufferwhen you specifically need thread safety - Use
Stringfor constants and simple cases
8 Summary
- String is immutable - modifications create new objects (slow for many changes)
- StringBuilder is mutable - modifies in place (fast, single-threaded)
- StringBuffer is mutable - modifies in place with locking (thread-safe)
- Multi-threading = multiple tasks running simultaneously
- Thread-safe = safe to use with multiple threads (uses locking)
- StringBuilder is ~1000x faster than String for many modifications
- Use StringBuilder for most cases when you need to modify strings frequently
Congratulations!
You now understand the differences between String, StringBuilder, and StringBuffer! In the next lesson, you'll practice these concepts with exercises.