← Back to Kotlin Course | Chapter 1: Setup & Basics | Lesson 5 of 7

The main() Function

The main() function is the special starting point that tells Kotlin exactly where to begin running your program.

Declaring main()

The simplest entry point is fun main() { ... }, which takes no parameters. This is enough for most command-line programs, including everything covered in this course.

Example: Declaring main()

markup
fun main() {
    println("main() with no parameters")
}

Accepting Command-Line Arguments

Kotlin also supports fun main(args: Array<String>), where args holds any arguments passed on the command line when the program is launched, such as java -jar app.jar hello world.

Note: If no arguments are passed, args is simply an empty array, not null.

Example: Accepting Command-Line Arguments

markup
fun main(args: Array<String>) {
    println("Received ${args.size} arguments")
    for (arg in args) {
        println("Argument: $arg")
    }
}

Calling Other Functions from main()

Real programs break work into smaller functions and call them from main. This keeps main short and readable, acting as a high-level outline of what the program does.

Example: Calling Other Functions from main()

markup
fun greet(name: String) {
    println("Hello, $name!")
}

fun main() {
    greet("Kotlin")
    println("Back in main() after calling greet()")
}

Program Exit

A Kotlin program ends naturally when main finishes running its last statement. Using return inside main exits it early, skipping any code written after that line.

Note: Avoid unreachable code after return -- the compiler will warn you about it.

Example: Program Exit

markup
fun main() {
    println("Before return")
    return
    // The next line would never run
}
Common Mistakes
  1. Defining more than one main() function in different files without realizing which one the build actually runs.
  2. Assuming main must always take a String array parameter; Kotlin also allows a parameterless fun main().
  3. Forgetting that code placed after a return inside main will never execute.
Chapter Summary
  • fun main() is the entry point of a standalone Kotlin program; execution always starts there.
  • Kotlin supports both fun main() and fun main(args: Array<String>) to optionally receive command-line arguments.
  • Only one main function should exist per compiled entry point; multiple files can each have their own if used as separate targets.
  • main can call other functions, and the program ends once main finishes executing.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.