Kotlin Input and Output: println, print and readln

Kotlin course · Basics · Lesson 9 of 51

So far your programs only printed fixed text. In this lesson you’ll print output in different ways, and read what the user types so your program can react to it.

Output: print and println

fun main() {
    print("Hello ")       // no new line after
    print("Kotlin")
    println()             // just a new line
    println("Line 1")     // text plus a new line
    println("Line 2")
}

Output:

Hello Kotlin
Line 1
Line 2

You can print any value, not just text. Kotlin calls toString() for you:

fun main() {
    println(42)
    println(3.5 * 2)
    println(true)
    println(listOf("a", "b", "c"))
}

Output:

42
7.0
true
[a, b, c]

Formatting output

fun main() {
    val name = "Asha"
    val total = 1234.5678

    println("Customer: $name")
    println("Total: %.2f".format(total))   // 2 decimal places
    println("%-10s|%5d|".format("Apples", 12)) // padded columns
}

Output:

Customer: Asha
Total: 1234.57
Apples    |   12|

Input: readln()

readln() waits for the user to type a line and press Enter, then returns it as a String:

fun main() {
    print("What's your name? ")
    val name = readln()
    println("Hello, $name!")
}

Output:

What's your name? Ravi
Hello, Ravi!

(The output shows what happens when the user types “Ravi”.)

Where do I type the input? In IntelliJ IDEA or Android Studio, type in the Run window at the bottom and press Enter. In the Kotlin Playground, input isn’t supported, so set the value in code instead.

readln() is available from Kotlin 1.6. Older code uses readLine(), which returns String? (it can be null) and needs readLine()!!. Use readln() in new code.

Reading numbers

readln() always returns text. Convert it to a number, using toIntOrNull() so a wrong entry doesn’t crash the program:

fun main() {
    print("Enter your age: ")
    val age = readln().toIntOrNull()

    if (age == null) {
        println("That's not a number")
    } else {
        println("Next year you'll be ${age + 1}")
    }
}

Output:

Enter your age: 17
Next year you'll be 18

Reading several values on one line

If the user types 10 20 30, split the line on spaces:

fun main() {
    print("Enter numbers separated by spaces: ")
    val numbers = readln().trim().split(" ").mapNotNull { it.toIntOrNull() }
    println("Sum = ${numbers.sum()}")
}

Output:

Enter numbers separated by spaces: 10 20 30
Sum = 60

Reading until the input ends

readlnOrNull() returns null when there’s no more input. That’s useful in competitive programming or when reading a file:

fun main() {
    var count = 0
    while (true) {
        val line = readlnOrNull() ?: break
        count++
        println("$count: $line")
    }
}

Output (when the input is three lines: apple, mango and banana):

1: apple
2: mango
3: banana

Common mistakes

  • Calling toInt() directly on input: readln().toInt() crashes on “abc” or an empty line. Use toIntOrNull().
  • Extra spaces: call trim() before converting or comparing.
  • Expecting input in the Playground: use IntelliJ IDEA or Android Studio to try programs that read input.

Exercise

Write a program that asks for two numbers and prints their sum, difference and product.

fun main() {
    print("First number: ")
    val a = readln().toIntOrNull() ?: 0
    print("Second number: ")
    val b = readln().toIntOrNull() ?: 0
    println()
    println("Sum: ${a + b}")
    println("Difference: ${a - b}")
    println("Product: ${a * b}")
}

Output:

First number: 8
Second number: 3

Sum: 11
Difference: 5
Product: 24

FAQ

What’s the difference between print and println?

println adds a new line after the text and print doesn’t.

What’s the difference between readLine and readln?

readln() returns a String and throws an error at the end of input. readLine() returns String?. Use readln() in new code.

How do I read an Int from the user in Kotlin?

val n = readln().toIntOrNull(), then handle the case where it’s null.

WhatsApp us📞 Call now