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

Your First Kotlin Program

Your first Kotlin program is a tiny set of instructions that tells the computer to display a message on the screen.

The main() Function

Every runnable Kotlin program needs an entry point function called main, marked with the fun keyword. When you run the compiled program, execution starts at the first line inside main's curly braces.

Example: The main() Function

markup
fun main() {
    println("Hello from main()")
}

Printing Hello, World

The classic first program in any language prints a greeting to the screen. In Kotlin, println("Hello, World!") does exactly that, sending the text to standard output followed by a newline.

Note: println adds a newline after the text; print does not.

Example: Printing Hello, World

markup
fun main() {
    println("Hello, World!")
}

Understanding the Syntax

Curly braces { } mark the start and end of the function body, and each statement inside typically sits on its own line. Unlike some languages, Kotlin does not require a semicolon at the end of each line.

Example: Understanding the Syntax

markup
fun main() {
    println("Curly braces group statements together")
    println("No semicolon needed at the end of a line")
}

Compiling and Running

Save the code in a file such as Hello.kt, then compile it with kotlinc Hello.kt -include-runtime -d hello.jar and run the result with java -jar hello.jar to see the output printed in your terminal.

Example: Compiling and Running

markup
fun main() {
    println("Saved as Hello.kt, compiled, then run")
}
Common Mistakes
  1. Forgetting the fun keyword before main, which is required to define any function in Kotlin.
  2. Misspelling println as print_ln or Println, causing a compiler error since Kotlin is case-sensitive.
  3. Leaving off the closing } for the main function body and getting a confusing 'expecting a top level declaration' error.
Chapter Summary
  • Every standalone Kotlin program needs a fun main() function as its entry point.
  • println() prints text followed by a newline; text must be wrapped in double quotes as a string.
  • Kotlin is case-sensitive, so Main, main, and MAIN are three different identifiers.
  • Kotlin source files typically end in .kt and are compiled with kotlinc.
🔒

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.