1. Introduction
When you’re just starting to program, string concatenation with + seems perfect: you simply take pieces of text and glue them into one. And that really is fine as long as there aren’t many pieces. But as soon as you introduce a loop, lots of lines, and “report assembly,” it suddenly turns out that naive concatenation creates too many intermediate strings — as if every time you rewrite the entire report from scratch, adding one letter.
String is immutable
A string (String) in Kotlin is immutable. That means: if you write val s2 = s1 + "!", then s1 didn’t “grow”; instead, a new string s2 was created. You can’t change the old string — “what’s written in ink cannot be erased,” so to speak.
This is convenient and safe, but sometimes expensive.
Bad pattern: += in a loop
Look at this example. It works, but there’s a catch:
fun main() {
var text = ""
for (i in 1..3) {
text += "Line No. $i\n"
}
print(text)
// Line No. 1
// Line No. 2
// Line No. 3
}
The problem here isn’t that the code is “wrong.” The problem is that on every iteration a new string text is created, and all the old contents are copied into it + the new piece. With three lines you won’t notice. With three thousand, your computer will start contemplating the meaning of life.
What we want instead
We need a tool that lets us “append text inside a single object” without recreating a giant string at each step. And that’s where StringBuilder enters the stage.
2. StringBuilder: what it is and how it works
If String is “an inscription carved in stone,” then StringBuilder is “a notepad with a pencil.” In a notepad, you can add lines one by one, erase, rearrange (within reason), and only at the end say: “Okay, now neatly rewrite this as a clean, beautiful string.”
StringBuilder is a special class for assembling text step by step. It stores an internal character buffer and can efficiently append to it.
Three main stages
It helps to keep a simple picture in mind:
flowchart LR
A["Text fragments"] --> B["StringBuilder (accumulate)"]
B --> C["toString() (get a finished String)"]
So the logic is: “accumulate” → “turn into a string” → “print/return.”
Minimal example: build a phrase
import kotlin.text.StringBuilder
fun main() {
val sb = StringBuilder()
sb.append("Hello")
sb.append(", ")
sb.append("world!")
println(sb.toString()) // Hello, world!
}
Notice: we’re not doing String + String + String. We’re appending into a single object sb, and at the end we call toString().
String and StringBuilder in plain words
String is a ready-to-use immutable string: it’s great for short values, templates like "Hello, $name", and situations where you build a string once and then only read it.
StringBuilder is a mutable “assembler”: it’s convenient when you build long text piece by piece, especially in a loop, and want to get the final String at the end via toString().
3. append() and appendLine() for assembling text
When you start writing reports, you quickly realize that “append a piece of text” and “append a whole line + a newline” are two different actions. Sure, you can always add "\n" by hand, but then you’ll quickly start getting confused: where you forgot a line break, where you added two line breaks in a row, where you accidentally stuck a space before \n. StringBuilder offers a more readable style.
append(...): added a piece
import kotlin.text.StringBuilder
fun main() {
val sb = StringBuilder()
sb.append("Total: ")
sb.append(10)
sb.append(" euros")
println(sb.toString()) // Total: 10 euros
}
The trick here is that append can accept not only strings, but also numbers and characters. Kotlin/Java will convert them to text for you.
appendLine(...): added a line and a line break
appendLine() is a handy thing: it adds text and a newline. In the Kotlin standard library it’s an extension function for StringBuilder, and you can call it in a chain, like a “report builder.”
import kotlin.text.StringBuilder
fun main() {
val sb = StringBuilder()
.appendLine("Report")
.appendLine("-----")
.appendLine("Status: OK")
print(sb.toString())
// Report
// -----
// Status: OK
}
What’s especially nice here is that appendLine(...) returns the same StringBuilder, so you can write it as a chain.
Empty line: appendLine() with no arguments
Sometimes you need some “air” between blocks.
import kotlin.text.StringBuilder
fun main() {
val sb = StringBuilder()
sb.appendLine("First part")
sb.appendLine() // empty line
sb.appendLine("Second part")
print(sb.toString())
// First part
//
// Second part
}
4. Good practices for using StringBuilder
A very common beginner problem is to make a StringBuilder global, pass it through ten functions, and have everyone append “whatever they want.” You can do that, but it quickly turns into a text version of something like “we have one shared wiring bundle in the project; don’t touch it; it’s held together by hope and prayers.”
A much better habit: inside a function, create a StringBuilder, assemble the text, and return a normal String.
Builder inside the function; outside — a String
import kotlin.text.StringBuilder
fun buildHeader(title: String): String {
val sb = StringBuilder()
sb.appendLine("====")
sb.appendLine(title)
sb.appendLine("====")
return sb.toString()
}
fun main() {
print(buildHeader("My report"))
// ====
// My report
// ====
}
There’s a very clear boundary here: the function returns a string, not a “semi-finished assembly object.” This is convenient for testing, for reading code, and for avoiding accidentally appending text to “the previous report.”
When you don’t need StringBuilder
After getting to know StringBuilder, some people get tempted: “Oh, if it’s fast, I’ll build absolutely everything with it.” It’s like getting a power screwdriver as a gift and then using it to open yogurt. Technically possible, but odd.
If you’re building one short string, especially using string templates, then + or a template is totally OK.
fun main() {
val name = "Ira"
val tasks = 3
println("User: $name, tasks: $tasks")
// User: Ira, tasks: 3
}
A rule that usually works: if a string is built in a loop, if you have lots of appendLine(...), or you want to assemble multiline text and return it from a function — StringBuilder is a great candidate. If the string is one short line — a template is simpler and clearer.
5. Practice: a list report for a mini task list
By this point in the course, you already have enough tools to build a simple console “task list” app without complex data structures: a fixed array of strings + a counter of occupied elements. We already know how to read a line, normalize it, parse a command via split(), use if/else, loops, and functions. Now we’ll add a nice task list output without turning the code into “100 lines of println.”
Let’s imagine the app state looks like this: there’s an array tasks and a number taskCount that tells how many tasks are actually filled.
Data stub
fun main() {
val tasks = Array(5) { "" }
var taskCount = 0
tasks[taskCount++] = "Buy milk"
tasks[taskCount++] = "Learn StringBuilder"
tasks[taskCount++] = "Don’t concatenate strings in a loop like a barbarian"
println("Total tasks: $taskCount") // Total tasks: 3
}
Bad output style: lots of println
You can do this, but it grows quickly:
fun main() {
val tasks = arrayOf("A", "B", "C")
println("Task list:")
println("1. ${tasks[0]}")
println("2. ${tasks[1]}")
println("3. ${tasks[2]}")
}
As soon as you have not three tasks but “however many the user enters,” you switch to a loop — and then you either have println inside the loop, or you assemble text. Printing inside a loop is fine, but sometimes we want to build a nice text first and then output it in one piece (for example, to easily reuse this text in other parts of the program).
Good style: assemble the report in a StringBuilder
Let’s make a function that returns a ready-to-use multiline report.
import kotlin.text.StringBuilder
fun buildTaskListReport(tasks: Array<String>, count: Int): String {
val sb = StringBuilder()
sb.appendLine("Task list:")
for (i in 0 until count) {
sb.appendLine("${i + 1}. ${tasks[i]}")
}
return sb.toString()
}
Now main can look clean:
fun main() {
val tasks = Array(5) { "" }
var taskCount = 0
tasks[taskCount++] = "Buy milk"
tasks[taskCount++] = "Learn StringBuilder"
print(buildTaskListReport(tasks, taskCount))
// Task list:
// 1. Buy milk
// 2. Learn StringBuilder
}
Notice we use print, not println: the report already contains line breaks, and an extra newline at the end isn’t always needed.
Numbering with alignment
In the previous lecture you learned padStart()/padEnd(). Let’s use them so the numbers don’t “jump around” if the task count becomes 12 or 123.
import kotlin.text.StringBuilder
fun buildTaskListReport(tasks: Array<String>, count: Int): String {
val sb = StringBuilder()
sb.appendLine("Task list:")
for (i in 0 until count) {
val num = (i + 1).toString().padStart(2)
sb.appendLine("$num. ${tasks[i]}")
}
return sb.toString()
}
If there are 3 tasks, you get:
1. ...
2. ...
3. ...
If there are 12 tasks, then:
9. ...
10. ...
11. ...
12. ...
And the text becomes visually more even, which means it’s easier to read.
6. Practice: help and error messages
When an application becomes even a little interactive, the console “user interface” is not just a list of data, but also hints: how to enter commands, what an error means, which examples are valid. Not the best approach is to store it as one huge string or many println. But if the hint is even slightly dynamic (for example, depends on the task limit), StringBuilder is very convenient again.
Building help text with StringBuilder
import kotlin.text.StringBuilder
fun buildHelp(maxTasks: Int): String {
val sb = StringBuilder()
sb.appendLine("Commands:")
sb.appendLine(" add <text> — add a task")
sb.appendLine(" list — show the list")
sb.appendLine(" exit — quit")
sb.appendLine()
sb.appendLine("Task limit: $maxTasks")
return sb.toString()
}
Usage:
fun main() {
val maxTasks = 5
print(buildHelp(maxTasks))
}
The benefit is that if you change the task limit, the help text will automatically be correct.
Unified message style: an error formatting function
import kotlin.text.StringBuilder
fun buildError(message: String): String {
val sb = StringBuilder()
sb.appendLine("Error:")
sb.appendLine(message)
return sb.toString()
}
fun main() {
print(buildError("Unknown command. Type help."))
// Error:
// Unknown command. Type help.
}
Yes, you could do "Error:\n$message\n". But as soon as the format becomes slightly more complex (a couple lines, an example, a hint) — a builder wins in readability.
7. Typical mistakes when working with StringBuilder
Mistake No. 1: keep doing text += ... inside a loop “out of habit.”
It’s not a “sin,” the compiler won’t scold you, and the program will work. But for long texts you’ll get extra intermediate strings and less predictable performance. StringBuilder is specifically made for the “append small pieces many times” scenario.
Mistake No. 2: forget toString() and try to print the builder as if it were a string.
In Kotlin, println(sb) will usually print the contents (because toString() gets called), and that’s sneaky: it looks like you can “do it that way.” But as soon as you start returning this value from a function or passing it along as a String, you’ll find out the type is not what you need. Good discipline: builder inside, only String outside.
Mistake No. 3: make one global StringBuilder for the whole app.
This quickly leads to “accidental text accumulation”: you built one report, then built a second, and it got stuck onto the first because nobody cleared the builder. It’s much safer to create the builder locally inside the function where you form a specific text, and convert it to a String there.
Mistake No. 4: mix up append() and appendLine() and get “stuck-together” output.
When a newline matters for readability, prefer appendLine. When you’re building a single line from parts (for example, a table row), prefer append. If you don’t distinguish these cases, either everything merges into one line, or you get weird empty lines.
Mistake No. 5: mix calculations and formatting in one giant append(...).
Sometimes you want to write a monster like sb.appendLine("Total: ${a + b * c - ...}"). The compiler will swallow it, but a human isn’t required to. It’s more readable to calculate into a val total = ... first, and then insert total into the string. You help yourself, and debugging becomes easier.
GO TO FULL VERSION