CodeBlanks Logo Icon CodeBlanks

StringBuilder

Learn efficient string concatenation with StringBuilder.

StringBuilder: efficient concatenation

In Kotlin String is immutable; each + creates a new object. If you concatenate a lot in a loop, StringBuilder is more efficient.

val sb = StringBuilder()
sb.append("Hello")
sb.append(" ")
sb.append("world")
val result = sb.toString()
// "Hello world"

StringBuilder grows the text in place; no new object per append. When you are done, call toString for the final string. With hundreds of appends the speed difference is clear.

StringBuilder vs String

String is immutable; + builds a new string every time. StringBuilder is mutable; append grows the same object.

var s = "a"
s = s + "b"   // new String object
val sb = StringBuilder("a")
sb.append("b")  // same object

With hundreds of appends + gets slow; each step copies. StringBuilder avoids this cost. For a one-line concat + is fine.

Practice Concatenate three parts

Create a StringBuilder; append "Hello", ", " and "world" with append. Take the result with toString and print it.

Starter code

Main.kt
fun main() {
    // Create a StringBuilder
    // Append three parts
    // Print the result with toString
}

Sample solution

Main.kt
val sb = StringBuilder()
sb.append("Hello")
sb.append(", ")
sb.append("world")
println(sb.toString())

Expected output

Merhaba, dünya

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match scenario to tool

Term Meaning
One-shot concat String +
Loop concat StringBuilder
Final text toString
Empty builder StringBuilder()

2 Fill in the blank: declare StringBuilder

Question
val sb = ____()
Answer
val sb = StringBuilder()

Explanation: StringBuilder() creates an empty builder.

3 You concatenate 1000 times in a loop. Which is faster?

  • String and +
  • Regex
  • StringBuilder and append Correct answer
  • matches

Explanation: StringBuilder does not create a new object per append.

All lessons in Beginner