StringBuilder
StringBuilder is a class used to create and modify text efficiently. Unlike String, a StringBuilder object is mutable, meaning its content can be changed directly without creating a brand-new object each time.
1. What is StringBuilder?
StringBuilder is a class used to create and modify text efficiently. Unlike String, a StringBuilder object is mutable, meaning its content can be changed directly without creating a brand-new object each time.
2. Why is it used?
When a program needs to build or modify text repeatedly — like constructing a long report line by line — using regular String would create many unnecessary objects, wasting memory. StringBuilder avoids this by modifying the same object directly.
3. Real-Life Example
Think of writing on a whiteboard versus writing on a fresh sheet of paper every single time you want to change a word. StringBuilder is like the whiteboard — you can erase and rewrite parts without needing a whole new sheet.
4. Syntax
javaStringBuilder sb = new StringBuilder(); sb.append("text"); sb.insert(position, "text"); sb.reverse();
5. Example Program
javapublic class StringBuilderDemo { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello"); sb.append(" Java"); System.out.println(sb); } }
Output:
Hello Java6. Key Points to Remember
StringBuilderis mutable — changes happen on the same object, without creating new ones each time.StringBuilderis not thread-safe, meaning it's not designed for safe use by multiple threads at once.- It's the preferred choice over
Stringwhen building or editing text repeatedly inside loops.