Command Palette

Search for a command to run...

Back to the lesson: Topic 6.3 — StringBuilder and StringBuffer
Core Java · Example 2 of 3 Java 5+

Length vs capacity: watching the array grow

The growth formula is an implementation detail of current JDKs; only the amortised O(1) behaviour is promised.

StringBuilder is a mutable, growable buffer of characters for building text step by step without creating a new String on every change; call toString() once at the end. StringBuffer is the older, synchronized twin, rarely needed today.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write static String repeatWithDash(String word, int times) that returns e.g. tea-tea-tea for ("tea", 3), using a StringBuilder. Print the results for 3 and 1.

02

Write static boolean isPalindrome(String s) using StringBuilder.reverse(), ignoring case. Test "Level", "chai" and "Racecar".

03

Build a multiplication table line for 7 (7 x 1 = 7 up to 7 x 5 = 35), one per line, in a single StringBuilder, and print it once.

Explain it without notes

01

Why is s = s + x in a loop slow, and how does StringBuilder fix it?

02

What's the difference between length() and capacity(), and how does the capacity grow?

03

When would you use StringBuffer instead of StringBuilder?

04

Why can't you use equals to compare two StringBuilders?

05

Is "Hello, " + name + "!" slower than using a StringBuilder?

Length vs capacity: watching the array grow Java 5+
Sign in to run this example in your browser.

Expected output

empty: length 0, capacity 16
16 chars: length 16, capacity 16
17 chars: length 17, capacity 34
setLength(5): length 5, capacity 34
trimToSize: length 5, capacity 5
text now: 01234
new StringBuilder("hello"): length 5, capacity 21
new StringBuilder(100): length 0, capacity 100