Answer
String vs StringBuilder vs StringBuffer
String — Immutable
Every modification creates a new String object in memory.
Java
String s = "Hello";
s = s + " World"; // creates NEW object — old "Hello" stays in pool
System.out.println(s); // "Hello World"
// Performance problem in loops:
String result = "";
for (int i = 0; i < 10000; i++) {
result += i; // creates 10000 new String objects! Very slow.
}
When to use: When the value won't change (passwords, config keys, constants).
✦
StringBuilder — Mutable, Fast, Not Thread-Safe
Modifies the same object in memory. Best for single-threaded string manipulation.
Java
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // modifies same object
sb.insert(5, ","); // "Hello, World"
sb.reverse(); // "dlroW ,olleH"
sb.delete(0, 6); // "olleH"
sb.replace(0, 2, "XX"); // "XXleH"
System.out.println(sb.toString());
// Efficient in loops:
StringBuilder sb2 = new StringBuilder();
for (int i = 0; i < 10000; i++) {
sb2.append(i); // modifies same object — fast!
}
Common StringBuilder methods:
| Method | Example | Result |
|---|---|---|
append(x) | sb.append("!") | Adds to end |
insert(i, x) | sb.insert(0, "Hi ") | Inserts at index |
delete(s, e) | sb.delete(0, 2) | Removes chars |
reverse() | sb.reverse() | Reverses string |
replace(s,e,x) | sb.replace(0,1,"A") | Replaces range |
length() | sb.length() | Returns length |
✦
StringBuffer — Mutable, Thread-Safe, Slower
Same as StringBuilder but all methods are synchronized — safe in multi-threaded code.
Java
StringBuffer sbf = new StringBuffer("Hello");
sbf.append(" World");
// Thread-safe: multiple threads can append without data corruption
✦
Comparison Table
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutable? | No | Yes | Yes |
| Thread-safe? | Yes (immutable) | No | Yes (synchronized) |
| Performance | Slow (new objects) | Fast | Medium |
| Introduced | Java 1.0 | Java 1.5 | Java 1.0 |
| Use when | Fixed values | Single-thread | Multi-thread |
In Automation Testing
Java
// Building dynamic XPaths or URLs — use StringBuilder
StringBuilder xpath = new StringBuilder("//div[@class='");
xpath.append(className).append("']//button[text()='");
xpath.append(buttonText).append("']");
driver.findElement(By.xpath(xpath.toString())).click();
// Building API request bodies dynamically
StringBuilder body = new StringBuilder("{");
body.append("\"name\":\"").append(userName).append("\",");
body.append("\"email\":\"").append(userEmail).append("\"}");
