User Input and Output
# 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()andprint().
-
Inject variables into Strings using String Templates (
$).
-
Read user input using
readln()(orreadLine()).
- Convert input strings to numbers.
- Build a Mini Project: User Registration System.
3. Output and String Templates
We already knowprintln() 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!
If you need to evaluate an *expression* (like math) inside a string, wrap it in curly braces ${ }:
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()).
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.
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().
7. Mini Project: User Registration System
Let's combine everything into a simple console application.8. Common Mistakes
-
Using
+for strings: Whileprintln("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. UsingOrNullparsing functions combined with the Elvis Operator?:guarantees your program will not crash.
10. Exercises
-
1.
Write a program that asks the user for the
priceof an item.
-
2.
Read the input and convert it safely to a
Double. (UsetoDoubleOrNull()).
- 3. Calculate a 10% tax.
- 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) $.
If you want to evaluate math inside a string template, what syntax must you use?
What function pauses the console and reads a line of text typed by the user?
What data type does readln() ALWAYS return?
If val age = "25", how do you convert it to an Integer?
What happens if you call "Hello".toInt()?
Which function safely attempts to convert text to a number, returning null if it fails?
What makes readln() better than the older readLine() in Kotlin?
In val data = readln().toIntOrNull() ?: 0, what happens if the user types "apple"?
+ 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()andtoIntOrNull(). 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'sreadln() 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 useif, else, and Kotlin's incredibly powerful when expression to control the flow of our programs.