What is the Difference Between String, StringBuilder, and StringBuffer?
String is immutable, while StringBuilder and StringBuffer are mutable. StringBuffer is thread-safe (synchronized), StringBuilder is not thread-safe (faster).
1. String (Immutable)
public class StringExample {
public static void main(String[] args) {
String str = "Hello";
// Every modification creates NEW object
String newStr = str.concat(" World");
System.out.println("Original string: " + str); // Hello (unchanged)
System.out.println("New string: " + newStr); // Hello World (new object)
System.out.println("Same object? " + (str == newStr)); // false
// Performance issue with many modifications
String result = "";
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
result += "a"; // Creates 10000 intermediate objects!
}
long time = System.currentTimeMillis() - start;
System.out.println("String concatenation time: " + time + "ms");
// Each += operation creates a new String object
// This is very inefficient for loops
}
}
2. StringBuilder (Mutable, Not Thread-Safe)
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
// Modifies same object - no new object created
sb.append(" World");
sb.append(" from");
sb.append(" Java");
sb.append("!");
System.out.println("StringBuilder result: " + sb);
// Other operations
sb.insert(5, " Beautiful");
System.out.println("After insert: " + sb);
sb.replace(6, 15, "Awesome");
System.out.println("After replace: " + sb);
sb.delete(5, 13);
System.out.println("After delete: " + sb);
sb.reverse();
System.out.println("After reverse: " + sb);
// Performance test
StringBuilder sbPerf = new StringBuilder();
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
sbPerf.append("a");
}
long time = System.currentTimeMillis() - start;
System.out.println("StringBuilder time: " + time + "ms");
// Additional methods
sbPerf.setCharAt(0, 'Z');
sbPerf.deleteCharAt(sbPerf.length() - 1);
// Capacity management
System.out.println("Capacity: " + sbPerf.capacity());
System.out.println("Length: " + sbPerf.length());
sbPerf.trimToSize();
System.out.println("After trim - Capacity: " + sbPerf.capacity());
}
}
3. StringBuffer (Mutable, Thread-Safe)
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
// Same API as StringBuilder
sb.append(" World");
System.out.println("StringBuffer result: " + sb);
// Thread-safe - methods are synchronized
// Can be safely used by multiple threads
// Capacity management
System.out.println("Initial capacity: " + sb.capacity());
System.out.println("Length: " + sb.length());
sb.ensureCapacity(100);
System.out.println("After ensureCapacity(100): " + sb.capacity());
sb.trimToSize();
System.out.println("After trimToSize: " + sb.capacity());
// Substring operations
String sub = sb.substring(0, 5);
System.out.println("Substring: " + sub);
// CharSequence operations
CharSequence seq = sb.subSequence(0, 5);
System.out.println("CharSequence: " + seq);
}
}
Performance Comparison
public class PerformanceTest {
public static void main(String[] args) {
int iterations = 50000;
// STRING (Very Slow)
long start = System.nanoTime();
String str = "";
for (int i = 0; i < iterations; i++) {
str += "a";
}
long stringTime = System.nanoTime() - start;
// STRINGBUILDER (Fastest)
start = System.nanoTime();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < iterations; i++) {
sb.append("a");
}
long builderTime = System.nanoTime() - start;
// STRINGBUFFER (Slightly slower due to synchronization)
start = System.nanoTime();
StringBuffer sbf = new StringBuffer();
for (int i = 0; i < iterations; i++) {
sbf.append("a");
}
long bufferTime = System.nanoTime() - start;
System.out.println("Performance Test (" + iterations + " iterations):");
System.out.println("String time: " + stringTime / 1_000_000 + " ms");
System.out.println("StringBuilder time: " + builderTime / 1_000_000 + " ms");
System.out.println("StringBuffer time: " + bufferTime / 1_000_000 + " ms");
// Speed ratio
System.out.println("
Speed comparison:");
System.out.println("StringBuilder is " + (stringTime / builderTime) + "x faster than String");
System.out.println("StringBuilder is " + (bufferTime / builderTime) + "x faster than StringBuffer");
}
}
Thread Safety Test
public class ThreadSafetyTest {
public static void main(String[] args) throws InterruptedException {
int iterations = 10000;
int threads = 10;
// StringBuilder - NOT Thread Safe
StringBuilder sb = new StringBuilder();
List builderThreads = new ArrayList<>();
for (int t = 0; t < threads; t++) {
Thread thread = new Thread(() -> {
for (int i = 0; i < iterations; i++) {
sb.append("a");
}
});
builderThreads.add(thread);
thread.start();
}
for (Thread t : builderThreads) {
t.join();
}
System.out.println("StringBuilder length (may be incorrect): " + sb.length());
System.out.println("Expected length: " + (iterations * threads));
System.out.println("Difference (lost updates): " + ((iterations * threads) - sb.length()));
// StringBuffer - Thread Safe
StringBuffer sbf = new StringBuffer();
List bufferThreads = new ArrayList<>();
for (int t = 0; t < threads; t++) {
Thread thread = new Thread(() -> {
for (int i = 0; i < iterations; i++) {
sbf.append("a");
}
});
bufferThreads.add(thread);
thread.start();
}
for (Thread t : bufferThreads) {
t.join();
}
System.out.println("
StringBuffer length (always correct): " + sbf.length());
System.out.println("Expected length: " + (iterations * threads));
// Concurrent modification example
System.out.println("
StringBuilder concurrent modification example:");
StringBuilder sharedSb = new StringBuilder("Start");
Runnable modifier = () -> {
for (int i = 0; i < 1000; i++) {
sharedSb.append("x");
// May cause corrupted state without synchronization
}
};
Thread t1 = new Thread(modifier);
Thread t2 = new Thread(modifier);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final length (may be corrupted): " + sharedSb.length());
}
}
Comparison Table
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread-Safe | Yes (immutable) | No | Yes (synchronized) |
| Performance | Slow for modification | Fastest | Moderate |
| Introduced | Java 1.0 | Java 1.5 | Java 1.0 |
| Equals()/HashCode() | Overridden | Not overridden | Not overridden |
When to Use Which?
public class WhenToUse {
public static void main(String[] args) {
// Use String for:
// - Constant values
// - Method parameters and return values
// - When immutability is desired
// - Small number of concatenations
String constant = "Fixed Value";
String concatenation = "Hello " + "World"; // Compiler optimizes
// Use StringBuilder for:
// - Single-threaded string manipulation
// - Large number of concatenations in loop
// - Building strings dynamically
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i);
sb.append(", ");
}
String result = sb.toString();
// Use StringBuffer for:
// - Multi-threaded string manipulation
// - Shared mutable string across threads
StringBuffer sbf = new StringBuffer();
// Example: Logging in multi-threaded environment
Runnable logger = () -> {
synchronized (sbf) {
sbf.append(Thread.currentThread().getName());
sbf.append(" logged at ");
sbf.append(System.currentTimeMillis());
sbf.append("
");
}
};
Thread t1 = new Thread(logger, "Thread-1");
Thread t2 = new Thread(logger, "Thread-2");
t1.start();
t2.start();
// Initial capacity for performance
// If you know approximate size, set initial capacity
StringBuilder optimized = new StringBuilder(1000); // Prevents resizing
System.out.println("
Recommendation:");
System.out.println("1. Use String for immutable data");
System.out.println("2. Use StringBuilder for single-threaded string building");
System.out.println("3. Use StringBuffer for multi-threaded string building");
System.out.println("4. Set initial capacity when size is known");
}
}
Master Java string handling with Online Learner!
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
