Strings in Java
Strings in Java
2. StringBuilder
Not Thread-Safe: Methods in StringBuilder are not
synchronized, so it’s not thread-safe. This makes it faster
than StringBuffer but means it should not be used where
multiple threads might access it simultaneously.
Performance: Generally faster than StringBuffer because
there is no synchronization overhead.
Use Case: Ideal for single-threaded applications or where
thread safety is not a concern.
StringBuilder builder = new StringBuilder("Hello");
builder.append(" World!");
System.out.println(builder); // Output: Hello World!
3. Similarities between StringBuffer and StringBuilder
Mutability: Both StringBuffer and StringBuilder are
mutable, meaning you can change their contents without
creating new objects (unlike String, which is immutable).
Methods: Both classes have similar methods, such as
append(), insert(), delete(), reverse(), and replace().
Initial Capacity: Both classes have an initial capacity of 16
characters (unless specified), and they automatically
expand as needed.
4. When to Use Which
Use StringBuffer if:
o Your application is multithreaded.
o You require thread-safe operations on strings.
Use StringBuilder if:
o You’re working in a single-threaded environment or
don’t require thread safety.
o You need faster performance for frequent string
manipulations.
Example Comparison
Here’s a simple performance comparison:
public class StringBufferBuilderDemo {
public static void main(String[] args) {
int n = 100000;
// StringBuilder
long startTime = System.nanoTime();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < n; i++) {
builder.append("a");
}
long endTime = System.nanoTime();
System.out.println("Time taken by StringBuilder: " +
(endTime - startTime) + " ns");
// StringBuffer
startTime = System.nanoTime();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < n; i++) {
buffer.append("a");
}
endTime = System.nanoTime();
System.out.println("Time taken by StringBuffer: " +
(endTime - startTime) + " ns");
}
}
In general, for most cases in single-threaded applications,
StringBuilder is preferred due to its better performance.