← Back to Chapters

Java StringBuilder

? Java StringBuilder

? Quick Overview

StringBuilder is a mutable sequence of characters in Java. Unlike String, it allows modification of content without creating new objects, making it faster and memory-efficient.

? Key Concepts

  • Mutable string class
  • Located in java.lang package
  • Not thread-safe (faster than StringBuffer)
  • Used for frequent string modifications

? Syntax / Theory

A StringBuilder object can grow or shrink dynamically. Common operations include append(), insert(), delete(), and reverse().

? Code Example

? View Code Example
// Demonstrates basic StringBuilder operations
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
sb.insert(5, ",");
sb.replace(0, 5, "Hi");
System.out.println(sb.toString());
}
}

? Live Output / Explanation

Output

Hi, World

The original string is modified directly without creating multiple objects, which improves performance.

? Interactive Playground

Simulate basic StringBuilder operations below:

"Start"
StringBuilder sb = new StringBuilder("Start");

✅ Tips & Best Practices

  • Use StringBuilder for heavy string concatenation
  • Avoid using it in multi-threaded environments
  • Convert to String only when final output is needed

? Try It Yourself

  • Create a StringBuilder and reverse a sentence
  • Build a string using a loop with append()
  • Compare performance with String concatenation