Kotlin Strings

Kotlin strings combine simple templating with a rich set of built-in methods for inspecting and transforming text.

String Basics and Templates

A String in Kotlin is an immutable sequence of characters created with double quotes. String templates let you embed expressions directly inside a string using $variableName for simple references or ${expression} for anything more complex.

String templates with $ and ${}

fun main() {
    val firstName = "Meera"
    val lastName = "Rao"
    val fullName = "$firstName $lastName"

    println("Hello, $fullName!")
    println("Your name has ${fullName.length} characters")
}

Multiline and Raw Strings

Triple-quoted strings (\"\"\"...\"\"\") preserve line breaks and do not require escaping backslashes or quotes, which makes them ideal for multi-line text blocks such as SQL queries or formatted messages.

Raw multiline strings with trimIndent()

fun main() {
    val poem = """
        Roses are red,
        Kotlin is fun,
        Null safety saves you
        Before code is run.
    """.trimIndent()

    println(poem)
}

Common String Methods

  • length: returns the number of characters
  • uppercase() / lowercase(): change casing
  • trim(): removes leading and trailing whitespace
  • split(delimiter): breaks a string into a List<String>
  • contains(text), startsWith(text), endsWith(text): search helpers returning Boolean
  • replace(old, new): substitutes one substring for another

Using built-in String methods

fun main() {
    val sentence = "  Kotlin is expressive and safe  "
    val cleaned = sentence.trim()

    println(cleaned.uppercase())
    println(cleaned.contains("safe"))
    println(cleaned.split(" "))
    println(cleaned.replace("safe", "concise"))
}
Method / OperatorPurposeExample
==Structural equality (content comparison)"abc" == "abc" -> true
equals(other, ignoreCase = true)Case-insensitive comparison"ABC".equals("abc", true) -> true
compareTo()Lexicographic ordering, returns Int"apple".compareTo("banana") -> negative
isEmpty() / isBlank()Check for empty or whitespace-only strings" ".isBlank() -> true
Note: Tip: Because Strings are immutable, every method like uppercase() or trim() returns a brand-new String rather than modifying the original; remember to store or print the result.
Note: Careful: String indices are zero-based, and out-of-range access such as fullName[100] on a short string throws a StringIndexOutOfBoundsException at runtime. Check length first or use getOrNull(index) when the index is uncertain.

Exercise: Kotlin Strings

Are String values in Kotlin mutable or immutable?