1. Introduction

Java programs often need to build text from smaller pieces: a shopping receipt, a product description, a report, or a list of names. Using the + operator is clear for a few pieces, but repeatedly concatenating strings inside a loop can create many temporary objects and repeatedly copy existing characters.

Premium Video

This video is available to Premium members or users who have purchased the course.

Sign in to Unlock

StringBuilder provides a mutable sequence of characters. You can append, insert, delete, replace, and reverse text in the same builder. When the text is ready, call toString() to obtain a regular immutable String.

Important rule: use + for a small, fixed number of pieces. Prefer StringBuilder when building text incrementally, especially inside loops.

2. Learning Objectives

After reading this article, you should be able to:

  • Explain why repeated string concatenation in a loop can be expensive.
  • Create a StringBuilder and understand its length and capacity.
  • Use append(), insert(), delete(), replace(), and reverse().
  • Read and update individual characters.
  • Convert a builder to a String and compare text correctly.
  • Choose between String, StringBuilder, and StringBuffer for common situations.

3. Why Repeated + Can Be Slow

A Java String is immutable: its character sequence cannot be changed after the object is created. An expression such as receipt = receipt + line creates a new result string. As the receipt grows, each iteration may copy the content accumulated so far into another string.

For a growing output of total length N, repeatedly copying the accumulated text can result in roughly quadratic work in the number of appended pieces. The precise cost depends on piece lengths and the Java implementation, but the pattern becomes costly for large loops.

Example: Concatenation with +

Output

Receipt:
Keyboard
Mouse
Monitor

The program works, but each loop iteration creates a new accumulated result. For a handful of items this is usually fine; for large dynamic output, StringBuilder is a better fit.

4. What Is StringBuilder?

StringBuilder is a class in java.lang, so it does not require an import. It maintains a mutable character buffer and tracks how much of that buffer is currently used.

  • Length is the number of characters currently stored.
  • Capacity is the amount of character storage available before the buffer needs to grow.
  • append() adds content at the end of the current sequence.
  • toString() produces a String containing the builder's current content.

The internal implementation details can vary by Java version, so focus on the public behavior: the builder can grow as needed and lets you modify its content without creating a new String for every append.

5. Creating and Using a StringBuilder

Output

Receipt:
Keyboard
Mouse
Monitor

Each call to append() writes into the same builder. The final toString() gives the completed text as an immutable String.

Whiteboard
Loading diagram...

6. Constructors, Length, and Capacity

Common constructors include:

ConstructorPurpose
new StringBuilder()Creates an empty builder with a default capacity, commonly 16 characters.
new StringBuilder(int capacity)Creates an empty builder with the requested initial capacity.
new StringBuilder(String text)Starts with the supplied text.
new StringBuilder(CharSequence seq)Starts with content from a character sequence.

Use length() to check how many characters are currently stored and capacity() to check the current buffer capacity. They are not the same value.

Typical output

first length: 0
first capacity: 16
second capacity: 50
third text: Order
third length: 5
third capacity: 21

The default and string-constructor capacities shown are typical Java behavior. If exact capacity matters, check it at runtime rather than treating it as a business rule.

7. Appending Different Types

append() has overloads for strings, characters, arrays, numbers, booleans, and objects. Primitive values are converted to text automatically.

Output

 Product: Wireless Mouse | Quantity: 2 | Price: $24.99 | In stock: true

Chaining calls

Because many mutating methods return the same builder, calls can be chained. This is convenient and does not require a separate intermediate String for every step.

Output

 Hello, customer!

A null reference passed to an append overload that accepts an object or character sequence is commonly represented as the text null. If null is not valid for your application, validate it explicitly instead of relying on that display behavior.

8. Inserting, Deleting, Replacing, and Reversing

MethodWhat it does
insert(offset, value)Inserts content at an index.
delete(start, end)Removes a range; start is inclusive and end is exclusive.
deleteCharAt(index)Removes one character.
replace(start, end, text)Replaces a range with new content.
reverse()Reverses the builder's character sequence.

Output

Java string Basics
Java Basics
Java Builder
redliuB avaJ

Indexes must be valid for the operation. Inserting or deleting near the beginning can require shifting the characters after that position, so append() is generally the most efficient common mutation.

9. Reading and Updating Individual Characters

charAt(index) reads the character at a zero-based index. setCharAt(index, ch) replaces the character at that index.

Output

A
B123
Length: 4

The valid character indexes range from 0 through length() - 1.

10. Changing the Logical Length

setLength(newLength) changes how many characters are considered part of the builder's content. A shorter length truncates the content. A longer length pads the additional positions with the null character ('\u0000'), not visible spaces.

Output

Note
Length: 4

Use a larger length only when padding with null characters is intended. For visible spaces or formatted fields, append the required spaces explicitly.

11. Managing Capacity

  • ensureCapacity(minimumCapacity) ensures that the builder can hold at least the requested capacity, growing the buffer if needed.
  • trimToSize() requests that the capacity be reduced to the current length.

If the approximate final size is known, providing an initial capacity can reduce buffer growth and copying. Do not call trimToSize() automatically on every short-lived builder: if the builder is immediately converted to a String and discarded, trimming is usually unnecessary.

Output shape

Length: 14
Capacity: at least 200
Capacity after trim: 14

The exact growth strategy is an implementation detail. The important point is that capacity can exceed length and the buffer grows when more space is required.

12. Converting to String

Call toString() when you need an immutable String, for example to return a result from a method or pass it to an API that specifically requires String.

Output

Order #1058
String

StringBuilder and String are different types. A builder supports mutation; a string is immutable.

13. Comparing StringBuilder Values Correctly

StringBuilder does not compare its text through an overridden equals() method. Two different builder objects containing the same characters are therefore not considered equal by equals(); the inherited behavior compares object identity.

Output

false
true

When you need to compare the contents, convert both builders to strings and compare those strings with equals().

14. String vs. StringBuilder vs. StringBuffer

FeatureStringStringBuilderStringBuffer
MutabilityImmutableMutableMutable
Best useFixed text and returned text valuesEfficient text construction in one threadMutable text when synchronized methods are required
Repeated appendsMay create intermediate stringsUsually efficientUsually efficient, with synchronization overhead
Thread-safety of individual methodsSafe to share because content is immutableNot synchronized; do not share for concurrent mutation without coordinationSynchronized methods provide thread-safe individual operations

Thread safety does not make a multi-step operation automatically atomic. If multiple threads need to update shared text as one coordinated action, design the synchronization around the whole operation.

15. + vs. StringBuilder: Which Should You Use?

Modern Java compilers optimize simple concatenation expressions, so + is perfectly appropriate for a small, fixed number of pieces:

For a loop that repeatedly adds to a growing result, prefer StringBuilder:

Output

 Products: Keyboard, Mouse, Monitor

The compiler can optimize a single concatenation expression, but it generally cannot combine separate loop iterations into one growing buffer automatically. For dynamic output, the builder makes the intended accumulation explicit.

Whiteboard
Loading diagram...

16. Performance and Complexity

Let N represent the total number of characters in the final output.

Operation patternTypical overall behaviorReason
Repeated result = result + piece in a loopCan approach quadratic copying as the result growsEach iteration may copy the accumulated text again
Appending all pieces to a StringBuilderAmortized linear in total appended charactersCharacters are written to a growing buffer; occasional growth copies the existing buffer
One toString() at the endLinear in the final output lengthProduces the immutable result string

The actual runtime depends on input sizes, JVM version, JIT compilation, and the surrounding program. Prefer clear code first, then measure performance if a workload is large enough for the difference to matter.

17. Common Mistakes

  1. Using + repeatedly inside a large loop. Use a builder for incremental construction.
  2. Confusing length() and capacity(). Length is the current content; capacity is available buffer space.
  3. Comparing builders with equals(). Compare first.toString().equals(second.toString()) when text equality is required.
  4. Forgetting toString(). A builder is not a String; convert when an API specifically requires a string.
  5. Using invalid indexes. insert, delete, replace, charAt, and setCharAt require valid positions and ranges.
  6. Assuming setLength() pads with spaces. Extending the logical length pads with null characters.
  7. Sharing one builder across threads without coordination. StringBuilder is not synchronized.
  8. Pre-sizing without a reason. Estimate capacity when useful, but do not overcomplicate small text-building tasks.

18. Best Practices

  • Use StringBuilder for loops and text assembled across multiple statements.
  • Use + for short, fixed concatenations when it reads more clearly.
  • Call toString() at the boundary where an immutable string is needed.
  • Set an initial capacity when the output size can be estimated reasonably.
  • Prefer append() for sequential construction; insertions and deletions in the middle can shift existing characters.
  • Validate indexes and input data before performing edits.
  • Do not use StringBuilder as a shared mutable object across threads without a synchronization strategy.
  • Keep performance claims proportional to the workload; benchmark realistic inputs when optimization decisions matter.

19. Quick Revision

  • StringBuilder is a mutable character sequence in java.lang.
  • append() adds content at the end and can be chained.
  • insert() adds content at an index; delete() removes a range; replace() substitutes a range; reverse() reverses the content.
  • length() reports used characters; capacity() reports available buffer capacity.
  • ensureCapacity() can request more room; trimToSize() can reduce excess capacity.
  • toString() returns the builder's content as an immutable String.
  • StringBuilder.equals() does not compare character content; compare converted strings instead.
  • Use + for small fixed expressions and StringBuilder for repeated or dynamic construction.

20. Conclusion

StringBuilder is Java's practical tool for constructing text efficiently. Its mutable buffer avoids repeatedly rebuilding an immutable string as content grows. Learn its core methods—especially append(), insert(), delete(), replace(), length(), capacity(), and toString()—and choose it whenever your program assembles a result piece by piece. For simple concatenation, keep using +; for loops and dynamic output, a builder is usually the clearer and more scalable choice.