Coding for All
Lesson 4: String Concatenation
String Concatenation Join two Strings together with +.
1fun main() {
2 val hello = "Hello"
3 val world = "World!"
4 println(hello + world)
5}
Terminal
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
HelloWorld!
Every line, explained
fun main() {
Every Kotlin program starts at the main function. When you run the program, Kotlin looks for fun main() and runs everything between its { and } from top to bottom.
val hello = "Hello"
A String is a piece of text. In Kotlin text always goes inside double quotes: "like this". Single quotes are only for one single character (like 'A'), so writing 'Hello' would be an error.
val world = "World!"
A String is a piece of text. In Kotlin text always goes inside double quotes: "like this". Single quotes are only for one single character (like 'A'), so writing 'Hello' would be an error.
println(hello + world)
Using + between two Strings glues them together; this is called concatenation. Kotlin joins them exactly as they are, without adding a space, so this prints HelloWorld!. To get a space you would write hello + " " + world.
}
This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.