Kotlin Input and Output

A program that never speaks or listens feels like a locked room. Kotlin gives you small, friendly tools to show messages on the screen and to read what a person types on the keyboard. Output and input together form the conversation between a user and your code.

Think of a Cafe Counter

Picture a counter at a small cafe. The customer says an order. The cashier repeats the order and announces the price. Your program works the same way. The keyboard carries the customer's voice, the program acts as the cashier, and the screen delivers the reply.

 Keyboard             Program              Screen
+-----------+       +------------+       +------------+
| "Tea"     | ----> | readln()   | ----> | println()  |
| typed by  |       | stores the |       | shows the  |
| the user  |       | text in a  |       | answer     |
+-----------+       | variable   |       +------------+
                    +------------+

Showing Output with print and println

Kotlin offers two functions for output. The println function prints the text and moves the cursor to a new line. The print function prints the text and keeps the cursor on the same line.

fun main() {
    println("Welcome to the cafe")
    print("Your order: ")
    print("Tea")
}

The program prints these two lines:

Welcome to the cafe
Your order: Tea

Printing Values Inside Text

A dollar sign inside quotes inserts a variable into the message. Kotlin calls this a string template.

val name = "Asha"
val cups = 2
println("$name ordered $cups cups")

Curly braces let you place a calculation inside the message:

println("Total: ${cups * 30} rupees")

Printing a Blank Line

Calling println() without any text prints an empty line. Blank lines separate sections of output and make long results easier to read.

Reading Input with readln

The readln function pauses the program and waits. The user types a line and presses Enter. The function hands that line back as a String.

fun main() {
    print("Enter your name: ")
    val name = readln()
    println("Hello, $name")
}

Older code uses readLine(). That function returns a nullable String, which means the result can be empty when no input exists. The readlnOrNull() function offers the same safe behavior in modern Kotlin.

Reading Numbers

Every typed value arrives as text, even when the user types digits. The text "25" is not the number 25. Conversion functions turn text into numbers.

fun main() {
    print("Enter your age: ")
    val age = readln().toInt()
    println("Next year you will be ${age + 1}")
}

Use toDouble() for values with decimals, such as prices or weights.

The Journey of a Typed Number

User types:   2 5 [Enter]
                 |
                 v
readln()      "25"        type: String
                 |
                 v
toInt()        25         type: Int
                 |
                 v
age + 1        26         ready for math

Reading Several Values from One Line

Users often type two values separated by a space. The split function cuts the text at each space and returns a list. A list stores items in order, and the numbering starts at 0.

fun main() {
    println("Enter two numbers separated by a space:")
    val parts = readln().split(" ")
    val a = parts[0].toInt()
    val b = parts[1].toInt()
    println("Sum = ${a + b}")
}

Handling Bad Input Safely

People make typing mistakes. A user may type "abc" when the program expects a number. The toInt() function crashes the program in that case. The toIntOrNull() function returns null instead of crashing, so your code can respond politely.

fun main() {
    print("Enter your age: ")
    val age = readln().toIntOrNull()
    if (age == null) {
        println("Please type digits only")
    } else {
        println("Your age is $age")
    }
}

Common Mistakes

  • Forgetting to convert text to a number before doing math.
  • Calling toInt() on text with spaces or letters.
  • Using print when a new line is needed, which joins messages together.
  • Typing the prompt with println when the answer should appear on the same line.

Quick Reference

FunctionJob
print()Shows text and stays on the line
println()Shows text and moves to a new line
readln()Reads one line as a String
readlnOrNull()Reads one line or returns null
toIntOrNull()Converts text to Int or returns null