Java: StringBuilder

StringBuilder is a mutable character sequence, ideal for scenarios that require frequent string modifications.

1. Why StringBuilder is Needed

String is immutable—every modification creates a new object, which is inefficient.

▶ Example: String vs StringBuilder

TEXT 📖 Display only
// String concatenation (inefficient)
String s = "";
for (int i = 0; i < 10000; i++) {
    s += "a";  // Creates a new object each time
}

// StringBuilder concatenation (efficient)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
    sb.append("a");  // Modifies the same object
}
String result = sb.toString();
💡 Performance difference: For 10,000 loop concatenations, StringBuilder is over 100x faster than String.


2. Creating StringBuilder

JAVA
// Empty StringBuilder
StringBuilder sb1 = new StringBuilder();

// With initial capacity
StringBuilder sb2 = new StringBuilder(100);

// With initial content
StringBuilder sb3 = new StringBuilder("Hello");

3. Common Methods

(1) append(): Add to End

TEXT 📖 Display only
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
sb.append(123);
System.out.println(sb);  // HelloWorld123

(2) insert(): Insert at Position

JAVA
StringBuilder sb = new StringBuilder("Hello");
sb.insert(5, " World");
System.out.println(sb);  // Hello World

(3) delete(): Delete Characters

TEXT 📖 Display only
StringBuilder sb = new StringBuilder("Hello World");
sb.delete(5, 6);  // Delete character at index 5 (space)
System.out.println(sb);  // HelloWorld

(4) replace(): Replace Characters

JAVA
StringBuilder sb = new StringBuilder("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb);  // Hello Java

(5) reverse(): Reverse String

TEXT 📖 Display only
StringBuilder sb = new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);  // olleH

(6) Other Methods

Method Description Example
charAt() Get character at index sb.charAt(0)
length() Current length sb.length()
capacity() Current capacity sb.capacity()
setCharAt() Set character at index sb.setCharAt(0,'h')
substring() Get substring sb.substring(0,3)

4. Method Chaining

StringBuilder methods return this, supporting method chaining.

JAVA
String result = new StringBuilder()
    .append("Hello")
    .append(" ")
    .append("World")
    .append("!")
    .toString();

System.out.println(result);  // Hello World!

▶ Example: Building SQL Statements

JAVA
public class SqlBuilder {
    public static String buildSelect(String table, String[] columns, String where) {
        StringBuilder sql = new StringBuilder("SELECT ");
        
        // Column names
        sql.append(String.join(", ", columns));
        sql.append(" FROM ");
        sql.append(table);
        
        // Condition
        if (where != null && !where.isEmpty()) {
            sql.append(" WHERE ");
            sql.append(where);
        }
        
        return sql.toString();
    }
    
    public static void main(String[] args) {
        String sql = buildSelect("users", 
            new String[]{"id", "name", "email"}, 
            "age > 18");
        System.out.println(sql);
        // SELECT id, name, email FROM users WHERE age > 18
    }
}
▶ Try it Yourself

▶ Example: Building HTML

JAVA
public class HtmlBuilder {
    public static String buildTable(String[][] data) {
        StringBuilder html = new StringBuilder();
        html.append("<table>\n");
        
        for (String[] row : data) {
            html.append("  <tr>\n");
            for (String cell : row) {
                html.append("    <td>").append(cell).append("</td>\n");
            }
            html.append("  </tr>\n");
        }
        
        html.append("</table>");
        return html.toString();
    }
    
    public static void main(String[] args) {
        String[][] data = {
            {"Alice", "25", "Engineer"},
            {"Bob", "30", "Designer"}
        };
        System.out.println(buildTable(data));
    }
}
▶ Try it Yourself

5. StringBuilder vs StringBuffer

Feature StringBuilder StringBuffer
Thread-safe No Yes
Performance Faster Slower
Use case Single-threaded Multi-threaded
💡 Recommendation: Use StringBuilder for single-threaded code. Use StringBuffer for multi-threaded code. Generally, StringBuilder is preferred.


6. Capacity and Growth

StringBuilder has a capacity concept and automatically grows when exceeded.

JAVA
StringBuilder sb = new StringBuilder();
System.out.println("Initial capacity: " + sb.capacity());  // 16

// Append content, grows when capacity exceeded
for (int i = 0; i < 20; i++) {
    sb.append("a");
}
System.out.println("Current capacity: " + sb.capacity());  // 34
System.out.println("Current length: " + sb.length());    // 20
💡 Growth rule: New capacity = old capacity * 2 + 2


7. ❓ Frequently Asked Questions

Q When should I use StringBuilder?
A When you need to modify strings frequently, such as in loop concatenations or building complex strings.
Q How do I choose between StringBuilder and String?
A Use String for few operations (simpler). Use StringBuilder for many operations (faster).
Q What's the default capacity of StringBuilder?
A 16 by default. You can specify it in the constructor.

❓ FAQ

Q Are strings mutable in Java?
A No. String objects are immutable. Every modification creates a new String.
Q Should I use == or equals for string comparison?
A Always use equals(). == compares references, not content.
Q How to efficiently concatenate many strings?
A Use StringBuilder instead of + in loops. It avoids creating many intermediate objects.

📖 Summary

📝 Exercises

  1. String concatenation: Use StringBuilder to concatenate numbers 1 to 100, separated by commas
  2. HTML building: Use StringBuilder to build an unordered list (ul/li)
  3. Performance test: Compare the time difference between String and StringBuilder for 10,000 concatenations

8. Next Lesson

In the next lesson, we'll learn about Math and Dates — the Math class and date/time API.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏