Your First Kotlin Program
Every Kotlin program, from a two-line greeting to a large Android app, is made of the same basic pieces: functions, statements and values. In this lesson you will write small programs, understand every word in them, print text in different ways, add comments and read what the user types.
Type the examples yourself in IntelliJ IDEA or the Kotlin Playground. Typing, making small mistakes and fixing them teaches you much more than reading.
The main function
When a Kotlin program starts, it looks for a function named main and runs the code inside it, from top to bottom.
fun main() {
print("Rohtak ")
print("to ")
println("Delhi")
println("Distance: about 70 km")
println()
println("Have a safe journey!")
}Rohtak to Delhi Distance: about 70 km Have a safe journey!
Here is what each part means:
funstarts a function, a named block of code.mainis the function's name. The namemainis special: it is the starting point.()holds the function's parameters. Thismainhas none.{and}mark the start and end of the function body.printlnprints its text and then moves to a new line.printprints without the line break, so the next output continues on the same line.println()with nothing inside prints an empty line.
Unlike Java, Kotlin does not need a class around main. A function written directly in a file, outside any class, is called a top-level function.
Each line inside the body is a statement, an instruction to do something. You do not end statements with semicolons. You only need a semicolon if you put two statements on one line, which is rarely a good idea.
Escape characters
Text inside double quotes is called a string. Some characters cannot be typed directly inside a string, so you write them with a backslash. This is called an escape sequence.
| Escape | Meaning |
|---|---|
\n | new line |
\t | tab |
\" | a double quote |
\\ | a backslash |
\$ | a dollar sign that is not a template |
fun main() {
println("She said \"Kotlin is fun\"")
println("Folder: C:\\kotlinc\\bin")
println("Write \$city to insert a value")
println("Line one\nLine two")
}She said "Kotlin is fun" Folder: C:\kotlinc\bin Write $city to insert a value Line one Line two
The dollar sign needs care because $ starts a string template (you saw $city in the previous lesson). Writing \$ prints a plain $.
Comments
Comments are notes for humans. The compiler ignores them. Use them to explain why something is done, not to repeat what the code obviously says.
// A single-line comment starts with two slashes.
/*
A block comment can span
several lines.
*/
/**
* A documentation comment (KDoc) describes the function below it.
* Editors show this text when you hover over the function name.
*/
fun main() {
println("Hello") // a comment can also follow code
// println("This line is switched off")
}Hello
Putting // in front of a line of code is a quick way to switch it off while testing. Kotlin also allows block comments inside other block comments, which Java does not.
Calling your own functions
You can write more top-level functions and call them from main. You will learn functions properly later; for now, see how one function can use another.
fun printHeader() {
println("==== Meera's Bakery, Kochi ====")
}
fun main() {
printHeader()
println("Plum cake: Rs 450")
println("Banana chips: Rs 120")
printHeader()
}==== Meera's Bakery, Kochi ==== Plum cake: Rs 450 Banana chips: Rs 120 ==== Meera's Bakery, Kochi ====
printHeader() runs the code inside that function each time you call it. The order of functions in the file does not matter: main can call a function written above or below it.
Reading input with readln
readln() waits for the user to type a line and press Enter, then gives you that line as a string. To get a number, convert the text with toInt() or toDouble().
fun main() {
print("Enter your name: ")
val name = readln()
print("How many tickets? ")
val tickets = readln().toInt()
println("Booked $tickets tickets for $name.")
println("Total: Rs ${tickets * 250}")
}A run where the user types Aarav and 3:
Enter your name: Aarav How many tickets? 3 Booked 3 tickets for Aarav. Total: Rs 750
${tickets * 250} puts the result of a calculation into the text. If the user types three instead of 3, toInt() fails with a NumberFormatException and the program stops. You will learn safe ways to handle this in Null Safety and Exceptions & Error Handling.
Program arguments
main can also accept the words typed after the program name on the command line. These arrive as an Array<String> named args.
fun main(args: Array<String>) {
println("You passed ${args.size} arguments")
println("First city: ${args[0]}")
}java -jar trip.jar Jaipur UdaipurYou passed 2 arguments First city: Jaipur
Most programs in this course use plain fun main(). Use the args version only when you need command-line arguments.
Common mistakes
- Wrong capital letters. Kotlin is case-sensitive:
PrintlnorMainwill not work. The compiler reports an "Unresolved reference" error for names it does not know. - Curly quotes. Copying code from a word processor can turn
"into“. Kotlin needs straight quotes. - Missing closing brace. Every
{needs a matching}. Good indentation (four spaces) makes this easy to see. - Forgetting the brackets on calls.
printHeaderwithout()does not call the function.
Key points
- A program starts at
fun main(); it needs no class around it. printlnprints a line;printprints without moving to a new line.- Escape sequences like
\n,\",\\and\$put special characters in strings. //,/* */and/** */write comments; the compiler ignores them.readln()reads a line of input as a string; convert it withtoInt()ortoDouble().fun main(args: Array<String>)receives command-line arguments.
Exercise
Write a program for Isha's tuition centre. It should print a header line, ask for the student's name and the number of months they want to join for, and then print a message with the total fee at Rs 1,200 per month. Add a comment that explains the fee rate.
Show solution
fun main() {
println("--- Isha's Tuition Centre ---")
print("Student name: ")
val name = readln()
print("Months: ")
val months = readln().toInt()
// The monthly fee is fixed at Rs 1200 for all classes.
println("$name, your fee for $months months is Rs ${months * 1200}.")
}A run where the user types Kabir and 4:
--- Isha's Tuition Centre --- Student name: Kabir Months: 4 Kabir, your fee for 4 months is Rs 4800.
readln().toInt() turns the typed text into a number so you can multiply it.
Quick Quiz
1. What is the difference between print and println?
println adds a line break after the text; print keeps the cursor on the same line.
2. How do you print a double quote inside a string?
A backslash before the quote tells Kotlin it is part of the text, not the end of the string.
3. What does readln() return?
readln() returns text; convert it with toInt() or toDouble() when you need a number.
4. Does a Kotlin main function need to be inside a class?
Kotlin allows top-level functions, so fun main() can sit directly in a file.
Learn Kotlin with a mentor
Free lessons get you started. Our Programming & Software Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
