String vs StringBuilder
In Java, String
is one of the most used data types, no matter what you build:
You store user input, email addresses, passwords.
You send and receive JSON, which is basically all text.
You create dynamic HTML, logs, URLs, queries โ all string manipulation.
Unlike primitive types, String
is an object โ it lives on the heap and comes with powerful built-in methods.
One unique thing about String
in Java is that it is immutable โ once created, you cannot change it.
Every โchangeโ you make creates a brand new String object in memory.
Example:
Even though it looks like you โchangedโ s
, Java secretly creates a new string in the background and makes s
point to it.
Why is immutability so important?
Multiple parts of your program can safely share the same string without worrying about someone else modifying it.
Strings are thread-safe by default โ no accidental overwrites.
It prevents bugs caused by unintended side effects.
BUT:
This immutability comes at a cost โ performance issues if you do lots of small edits.
Why? Because you keep creating new objects that the JVM must allocate and garbage collect.
When you need to build, append, or modify large or complex strings many times, using plain String
is inefficient.
StringBuilder is designed to solve this:
It is mutable, meaning the internal character array can change.
It keeps all edits inside the same object โ no new object each time.
Itโs perfect for loops, file generation, JSON/XML builders, dynamic queries, and anywhere you keep adding to the same text.
Real world:
Creating an email template from 50 small pieces โ StringBuilder
.
Generating CSV/TSV rows โ StringBuilder
.
Logging lots of messages in loops โ StringBuilder
.
โ
Pro Tip:
Use StringBuilder
when:
You have many string edits inside a loop.
You need best performance for massive text processing.
The temporary string doesnโt need to be thread-safe โ StringBuilder
is not synchronized (faster).
If you need thread safety, use StringBuffer
โ same API, but synchronized.
However, StringBuffer
is rare these days โ StringBuilder
is the modern go-to.
Below is an expanded Mini Lab showing how different String
and StringBuilder
really are when handling repeated appends.
Key takeaway:
With String
, each loop makes a new object, copies the old characters, adds one โ repeat 10,000 times = massive waste.
StringBuilder
works in-place โ same buffer, just expands as needed.
In real apps, this difference can make or break API response times, especially when building long responses.