Operators & Strings
Reviewed & published by Brayan K
Kotlin is a modern, concise language with a familiar set of operators for arithmetic, comparison, and logic — plus first-class string templates that make building text effortless.
Part of the free Kotlin course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.
By the end of this lesson you'll know how every common operator behaves (including the gotcha of integer division) and how to manipulate strings with templates and built-in functions.
What You'll Learn in This Lesson
- Arithmetic operators + - * / % and integer division
- Comparison operators and the Boolean results they return
- Logical operators && || ! for combining conditions
- Building strings with templates instead of concatenation
- Useful String functions: uppercase, trim, replace, startsWith
- Multi-line strings with triple quotes and trimIndent
1️⃣ Arithmetic, Comparison, and Logic
Kotlin's operators will look familiar from maths and other languages. The one trap to remember: when both sides of / are integers, the result is an integer — the fractional part is thrown away. Make one side a Double to get a decimal result.
fun main() {
// Arithmetic operators
println(7 + 3) // -> 10
println(7 - 3) // -> 4
println(7 * 3) // -> 21
println(7 / 3) // -> 2 (Int division truncates!)
println(7 % 3) // -> 1 (remainder / modulo)
println(7.0 / 3) // -> 2.3333333333333335 (one Double = Double result)
// Comparison operators return a Boolean
println(5 > 3) // -> true
println(5 == 5) // -> true
println(5 != 3) // -> true
// Logical operators: && (and), || (or), ! (not)
val sunny = true
val warm = false
println(sunny && warm) // -> false
println(sunny || warm) // -> true
println(!warm) // -> true
}Comparisons (>, ==, !=) always produce a Boolean, and the logical operators &&, ||, and ! let you combine those booleans into bigger conditions.
2️⃣ Strings and Templates
Strings in Kotlin come with a rich toolbox. Templates ($var and ${expr}) are the idiomatic way to build text, and methods like uppercase(), trim(), and replace() transform strings without fuss.
fun main() {
val first = "Grace"
val last = "Hopper"
// String templates beat + concatenation:
println("$first $last") // -> Grace Hopper
println("Name length: ${first.length}") // -> Name length: 5
// Handy String functions:
println(first.uppercase()) // -> GRACE
println(last.lowercase()) // -> hopper
println(" spaced ".trim()) // -> spaced
println(first.startsWith("Gr")) // -> true
println("$first $last".replace("o", "0"))// -> Grace H0pper
// Multi-line strings use triple quotes:
val poem = """
Roses are red,
Kotlin is neat.
""".trimIndent()
println(poem)
}Triple-quoted strings keep line breaks exactly as written; .trimIndent() strips the shared indentation so your source stays tidy while the output is clean.
Your turn. Replace each TODO with the right operator, then run and compare.
// 🎯 YOUR TURN — replace each TODO then run main()
fun main() {
val price = 20
val quantity = 3
// 1) Compute the total with the right operator
val total = price TODO quantity // 👉 replace TODO with *
// 2) Is the total over 50? (a comparison, gives a Boolean)
val isBig = total TODO 50 // 👉 replace TODO with >
// 3) Build a message with a string template
println("Total: $total, big order: $isBig")
// ✅ Expected: Total: 60, big order: true
}Mini-Challenge: A Receipt Formatter
Combine arithmetic, a comparison, and a string template (with uppercase()) into one tidy receipt line.
// 🎯 MINI-CHALLENGE: a tiny receipt formatter.
// Save as Receipt.kt and run main().
//
// 1. Set item = "Coffee", unitPrice = 3, qty = 4.
// 2. Compute subtotal = unitPrice * qty.
// 3. Decide freeShipping = subtotal >= 10 (a Boolean).
// 4. Print a receipt line using a string template, including
// the item in UPPERCASE via .uppercase().
//
// ✅ Example output:
// 4 x COFFEE = 12 | free shipping: true
fun main() {
// your code here
}Common Errors (and the fix)
- Unexpected integer division — 5 / 2 is 2, not 2.5. Make one operand a Double: 5.0 / 2.
- Using = instead of == — = assigns; == compares. In Kotlin == compares values (calls equals).
- Forgetting ${ } for expressions — "$a + $b" prints the numbers and a literal +. Use "${a + b}" to print the sum.
- Indented triple-quoted output — Without .trimIndent() your output keeps the source indentation. Add it to clean things up.
Pro Tips
- 💡 Even check: n % 2 == 0 is true for even numbers — a classic use of modulo.
- 💡 Compare with == freely: unlike Java, Kotlin's == on strings compares contents, not references.
- 💡 Short-circuiting: && and || stop evaluating as soon as the result is known — handy for null guards.
📋 Quick Reference — Operators & Strings
| Concept | Kotlin Syntax |
|---|---|
| Remainder | a % b |
| Equality | a == b |
| Logical and / or | a && b, a || b |
| Template variable | "Hi $name" |
| Template expression | "${a + b}" |
| Multi-line string | """ ... """.trimIndent() |
🎉 Lesson Complete!
- ✅ Arithmetic: + - * / % — beware integer division
- ✅ Comparisons return a Boolean
- ✅ Logic: && || ! combine conditions
- ✅ String templates beat + concatenation
- ✅ Triple quotes give multi-line strings; trimIndent() cleans them up
Practice quiz
What does 7 / 3 evaluate to in Kotlin?
- 2.33
- 2
- 3
- 2.5
Answer: 2. When both operands are integers, Kotlin performs integer division and truncates to 2.
How do you make 7 / 3 produce a decimal result?
- Use 7 // 3
- Make at least one operand a Double, like 7.0 / 3
- Use 7 % 3
- It is impossible
Answer: Make at least one operand a Double, like 7.0 / 3. If one operand is a Double, the whole expression becomes a Double.
What does the % operator compute?
- The percentage of a number
- Integer division
- The remainder after division
- Exponentiation
Answer: The remainder after division. % returns the remainder, so 7 % 3 is 1.
What does 7 % 3 evaluate to?
- 2
- 0
- 3
- 1
Answer: 1. 3 goes into 7 twice with 1 left over, so the remainder is 1.
Which operators are the logical and, or, and not?
- & | ~
- && || !
- and or not only
- AND OR NOT
Answer: && || !. Kotlin uses && for and, || for or, and ! for not.
What type does a comparison like 5 > 3 produce?
- Int
- String
- Boolean
- Double
Answer: Boolean. Comparison operators always produce a Boolean.
Which is the idiomatic way to insert a value into a string?
- "Hi " + name
- String.format with %s
- A string template like "Hi $name"
- Concatenating with commas
Answer: A string template like "Hi $name". String templates with $ are clearer and the idiomatic choice.
How do you embed an expression (not just a variable) in a template?
- $a + b
- ${a + b}
- #{a + b}
- {a + b}
Answer: ${a + b}. Use ${ } around an expression; bare $ only works for a simple variable.
What do triple-quoted strings provide?
- Automatic encryption
- Raw, multi-line strings that preserve line breaks
- Faster concatenation
- Compile-time constants only
Answer: Raw, multi-line strings that preserve line breaks. Triple-quoted strings are raw multi-line strings; trimIndent() cleans up indentation.
In Kotlin, what does == compare for two strings?
- Their memory references
- Their contents, by calling equals
- Their lengths only
- Nothing, it is a syntax error
Answer: Their contents, by calling equals. Unlike Java, Kotlin's == compares values (calls equals), so string contents are compared.
Continue this course
- Previous: Null Safety
- Next: Control Flow & when — Make decisions with if expressions and the powerful when statement
- Quick reference: Kotlin cheat sheet
Frequently asked questions
Why does 7 / 3 give 2 instead of 2.33?
When both operands are integers, Kotlin performs integer division and discards the fractional part, so 7 / 3 is 2. To get a decimal result, make at least one operand a Double: 7.0 / 3 or 7 / 3.0 gives 2.333…. You can also convert explicitly with 7.toDouble() / 3. This behaviour is consistent with Java and most C-family languages.
Should I use string templates or + to build strings?
Prefer string templates. Writing "Hello $name, you have ${count} items" is clearer and less error-prone than "Hello " + name + ", you have " + count + " items". Templates handle the conversion to text for you and read almost like the final sentence. Use + only for the simplest one-piece joins or when concatenating in a loop where a StringBuilder would be even better.
What does the % (modulo) operator do?
The % operator returns the remainder after division. For example 7 % 3 is 1 because 3 goes into 7 twice with 1 left over. It is extremely useful for tasks like checking whether a number is even (n % 2 == 0), wrapping values around a range, or grouping items into buckets. It works with both integer and floating-point numbers.
What are triple-quoted strings for?
Triple-quoted ("""…""") strings are raw, multi-line strings: they preserve line breaks and do not process escape sequences like . They are perfect for embedding JSON, SQL, HTML, or any block of text. Combine them with .trimIndent() to remove the common leading whitespace so your code can stay nicely indented while the output is clean.