Joining with separators, and builder equality
StringBuilder.compareTo arrived in Java 11; String.join and StringJoiner in Java 8.
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.
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.
Write static boolean isPalindrome(String s) using StringBuilder.reverse(), ignoring case. Test "Level", "chai" and "Racecar".
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
Why is s = s + x in a loop slow, and how does StringBuilder fix it?
What's the difference between length() and capacity(), and how does the capacity grow?
When would you use StringBuffer instead of StringBuilder?
Why can't you use equals to compare two StringBuilders?
Is "Hello, " + name + "!" slower than using a StringBuilder?
Expected output
builder: tea, samosa, cake
String.join: tea, samosa, cake
join a List: a | b | c
StringJoiner: [tea, samosa, cake]
empty joiner: nothing ordered
x.equals(y): false
x.compareTo(y) == 0: true
contentEquals: true