Creating strings
- Kotlin course
- Beginner
- Lesson 30/116
- 4 min
Learn to create strings and use the length property.
Creating strings
A String holds text and is written in double quotes. For example val s = "Hello" creates a String. In Kotlin, Strings are immutable: once created, their content does not change.
val s = "Kotlin"
println(s.length) // 6The length of a String is given by the length property. Unlike Java, there are no parentheses; length is a property, not a method. The first character has index 0, the last has index length - 1. Going beyond throws IndexOutOfBoundsException.
length is a property
In Kotlin, length is a property, not a method. So no parentheses are used: s.length is correct, s.length() is wrong.
val s = "Hello"
val n = s.length // 5
// s.length() // compile errorIn Java, length() is a method and needs parentheses. When moving to Kotlin this is a common mix-up; the compiler warns you at build time.
For the empty String "", length returns 0.
Practice Create a string and print its length
Write a fun main(). Assign "Alex" to val name. Print the string with println(name) and its length with println(name.length) on separate lines.
Starter code
fun main() {
// Print the string and its length
}Sample solution
fun main() {
val name = "Alex"
println(name)
println(name.length)
}Expected output
Alex 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does "Kotlin".length return?
- 5
- 6 Correct answer
- 7
- 0
Explanation: "Kotlin" has 6 characters, length returns 6.
2 Complete the length call
val n = name.____
val n = name.length
Explanation: name.length gives the length (no parens).
3 Match the string concepts
| Term | Meaning |
|---|---|
length |
Length |
"Hello" |
String example |
0 |
First index |
length - 1 |
Last index |