After understanding why Java Strings are immutable, another question came to my mind:
If Strings can't change... how do we efficiently build large pieces of text?
Consider this:
String report = "";
for (int i = 1; i <= 10000; i++) {
report += "Test Passed\n";
}
Looks simple.
But every time we use +, Java creates a new String object because Strings are immutable.
That means thousands of unnecessary objects may be created while building one report.
Now imagine doing that inside a large automation framework.
That's where StringBuilder comes in.
Instead of creating a new object every time, it modifies the same object internally.
Think of it like writing on a whiteboard.
With a String, every change means getting a brand-new whiteboard.
With StringBuilder, you're simply writing on the same one.
When you're finally done, you call:
toString()
Only then does Java create the final immutable String.
That was my biggest takeaway.
StringBuilder isn't just another Java class.
It exists to solve a very specific performance problem created by immutable Strings.
The moment I understood the problem, remembering the solution became easy.
That's something I'm trying to apply to every Java topic I learn:
Don't memorize the class. Understand why it exists.