Skip to main content

String Builder

We know that strings in Java are immutable. This is exactly why string concatenation is costly. It always creates a new object and copies the data from the old one.

StringBuilder Class

It exposes the underlying character array. You can change the characters directly. This avoids new string objects and data copies. It's faster.

size of StringBuilder array

StringBuilder uses a character array, so it has a capacity. When you exceed it, a new larger array is made and the data is copied over.

Setting the initial size helps control the Big O of the work.

String Pools

JVM has a string pool, but this is only for strings that are created using string literals.

During class loading, all string literals in the code go into the pool. If a literal is already there, the JVM returns the existing object's reference. It doesn't create a new one.

strings created at runtime

For strings made at runtime, the pool isn't used at all.

You can still add them by hand with the intern() method. Otherwise, the runtime pool is only used when you reference existing string literals.