How to Create String in Kotlin: Syntax and Examples
In Kotlin, you create a string by enclosing text within double quotes using
"your text". You can also create multi-line strings using triple quotes """your text""".Syntax
To create a string in Kotlin, use double quotes for a single-line string. For multi-line strings, use triple double quotes. Strings are immutable, meaning once created, they cannot be changed.
- Single-line string: Enclose text in
"". - Multi-line string: Enclose text in
"""to keep line breaks and formatting.
kotlin
val singleLine: String = "Hello, Kotlin!" val multiLine: String = """ This is a multi-line string. """
Example
This example shows how to create and print both single-line and multi-line strings in Kotlin.
kotlin
fun main() {
val greeting: String = "Hello, Kotlin!"
val poem: String = """
Roses are red,
Violets are blue,
Kotlin is fun,
And so are you!
"""
println(greeting)
println(poem)
}Output
Hello, Kotlin!
Roses are red,
Violets are blue,
Kotlin is fun,
And so are you!
Common Pitfalls
Common mistakes include using single quotes instead of double quotes, which is for characters, not strings. Also, forgetting to use triple quotes for multi-line strings causes errors or unwanted escape characters.
kotlin
fun main() {
// Wrong: single quotes for string
// val wrongString = 'Hello' // Error: Char expected
// Right: double quotes for string
val rightString = "Hello"
// Wrong: multi-line string without triple quotes
// val wrongMulti = "Line1\nLine2" // Works but escapes needed
// Right: multi-line string with triple quotes
val rightMulti = """
Line1
Line2
"""
println(rightString)
println(rightMulti)
}Output
Hello
Line1
Line2
Quick Reference
| Concept | Syntax | Description |
|---|---|---|
| Single-line string | "Hello" | Text enclosed in double quotes |
| Multi-line string | """Text More text""" | Text enclosed in triple quotes preserving line breaks |
| Character | 'a' | Single character enclosed in single quotes |
| Immutable | val text = "Hi" | Strings cannot be changed after creation |
Key Takeaways
Create strings using double quotes for single-line text in Kotlin.
Use triple double quotes for multi-line strings to preserve formatting.
Single quotes are for characters, not strings.
Strings in Kotlin are immutable and cannot be changed once created.
Remember to use println() to display strings in the console.