Kotlin – Create a String

Create a String in Kotlin

To create a String in Kotlin, you can use double quotes or String() constructor.

1. Create String using Double Quotes

To create a string using double quotes, enclose the sequence of character in the double quotes.

"Hello World"

You can assign this string value to a variable, or use it in an expression.

val message = "Hello World"

In the following program, we create a string using double quotes, assign it to a variable, and print it to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val message = "Hello World"
    println(message)
}

Output

Hello World

2. Create String using String() Constructor

In Kotlin, there is String class. We can use its constructor to create a String.

Call the String() constructor and pass the array of characters as argument. The constructor returns a string value.

val message = String(charArrayOf('a', 'p', 'p', 'l', 'e'))

In the following program, we create a string using double quotes, assign it to a variable, and print it to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val message = String(charArrayOf('a', 'p', 'p', 'l', 'e'))
    println(message)
}

Output

apple