Skip to main content
Kotlin Basics
CHAPTER 06 Beginner

User Input and Output

Updated: May 18, 2026
5 min read

# CHAPTER 6

User Input and Output

1. Chapter Introduction

Programming is about interactivity. An application must accept data from a user, process it, and output a result. In this chapter, we will learn how to read data typed into the console, convert that text into usable data types (like Integers), and format our output beautifully using Kotlin's powerful String Templates.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Output data clearly using println() and print().
  • Inject variables into Strings using String Templates ($).
  • Read user input using readln() (or readLine()).
  • Convert input strings to numbers.
  • Build a Mini Project: User Registration System.

3. Output and String Templates

We already know println() prints text to the screen. But what if we want to print text combined with a variable?

In Java, you have to use String Concatenation (+), which is messy: System.out.println("Hello " + name + ", you are " + age + " years old.");

Kotlin String Templates ($): Kotlin allows you to embed variables directly inside the double quotes using the $ symbol!

kotlin
1234567
fun main() {
    val name = "Alice"
    val age = 28
    
    // Using String Templates (Clean and readable!)
    println("Hello $name, you are $age years old.")
}

If you need to evaluate an *expression* (like math) inside a string, wrap it in curly braces ${ }:

kotlin
12
val items = 5
println("Total items plus one is: ${items + 1}")

4. Reading User Input (readln())

To pause the program and wait for the user to type something into the console, we use the readln() function (introduced in Kotlin 1.6 as the safer replacement for readLine()).
kotlin
12345678
fun main() {
    print("Please enter your name: ")
    
    // Pauses and waits for the user to type and press Enter
    val name = readln() 
    
    println("Welcome to Kotlin, $name!")
}

5. Parsing Input to Numbers

readln() ALWAYS returns a String. Even if the user types 25, Kotlin sees it as text "25". If we want to do math with it, we must explicitly convert it using Parsing.
kotlin
123456789
fun main() {
    print("Enter your age: ")
    val ageString = readln()
    
    // Convert the String to an Int using .toInt()
    val ageInt = ageString.toInt() 
    
    println("Next year, you will be ${ageInt + 1} years old.")
}

6. Safe Parsing (Preventing Crashes)

What if the user types "Twenty" instead of "20"? .toInt() will crash the program with a NumberFormatException! Kotlin provides a safer alternative: .toIntOrNull().
kotlin
1234567891011
fun main() {
    print("Enter your age: ")
    
    // Returns null if the input is not a valid number
    val age = readln().toIntOrNull() 
    
    // Using the Elvis operator to default to 0 if they typed garbage
    val finalAge = age ?: 0 
    
    println("Recorded age: $finalAge")
}

7. Mini Project: User Registration System

Let's combine everything into a simple console application.
kotlin
1234567891011121314151617
fun main() {
    println("--- USER REGISTRATION ---")
    
    print("Enter Username: ")
    val username = readln()
    
    print("Enter Birth Year: ")
    // Chain readln() directly into toIntOrNull()
    val birthYear = readln().toIntOrNull() ?: 2000
    
    val currentYear = 2024
    val age = currentYear - birthYear
    
    println("\n--- REGISTRATION COMPLETE ---")
    println("Profile for $username created successfully.")
    println("Calculated Age: $age")
}

8. Common Mistakes

  • Using + for strings: While println("Hello " + name) works, it is considered unidiomatic Kotlin. Always use String Templates ($name).
  • Forgetting to Parse: Trying to do math directly on the result of readln(): val x = readln() + 5. The compiler will throw an error because you are trying to add a number to text.

9. Best Practices

  • Always use toIntOrNull(): When dealing with human input, assume the user will make a mistake. Using OrNull parsing functions combined with the Elvis Operator ?: guarantees your program will not crash.

10. Exercises

  1. 1. Write a program that asks the user for the price of an item.
  1. 2. Read the input and convert it safely to a Double. (Use toDoubleOrNull()).
  1. 3. Calculate a 10% tax.
  1. 4. Print the final price using a String Template.

11. MCQs with Answers

Q1. Which symbol is used for String Templates in Kotlin to inject a variable into text? a) & b) # c) $ Answer: c) $.

Question 2

If you want to evaluate math inside a string template, what syntax must you use?

Question 3

What function pauses the console and reads a line of text typed by the user?

Question 4

What data type does readln() ALWAYS return?

Question 5

If val age = "25", how do you convert it to an Integer?

Question 6

What happens if you call "Hello".toInt()?

Question 7

Which function safely attempts to convert text to a number, returning null if it fails?

Question 8

What makes readln() better than the older readLine() in Kotlin?

Question 9

In val data = readln().toIntOrNull() ?: 0, what happens if the user types "apple"?

Q10. Is it recommended to use the + operator to combine strings and variables in Kotlin? a) Yes b) No, String Templates ($) are much cleaner and preferred. Answer: b) No, String Templates are preferred.

12. Interview Questions

  • Q: Explain the difference between toInt() and toIntOrNull(). Why is the latter preferred for user input?
  • Q: What is a String Template in Kotlin, and why is it superior to String Concatenation?

13. Summary

Interactivity breathes life into applications. Kotlin's readln() makes capturing user input trivial, while functions like toIntOrNull() provide robust, crash-free data conversion. Finally, String Templates drastically clean up output formatting, ending the era of messy Java string concatenation.

14. Next Chapter Recommendation

Our applications run in a straight line, but real apps need to make decisions! In Chapter 7: Conditional Statements, we will learn how to use if, else, and Kotlin's incredibly powerful when expression to control the flow of our programs.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·