Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 134 ยท Getting Started

How Kotlin Code Runs

Understand how Kotlin source becomes a running program - kotlinc, JVM bytecode, the standard library, compile errors vs run-time errors, scripts, projects and IDEs.

When you press Run on this page, a surprising amount happens in a few seconds: your text is checked, translated, packaged and executed. Knowing the journey from source file to running program makes everything else easier. Error messages stop being mysterious, you know why a Kotlin program starts slower than a shell script, and you understand how Kotlin can live inside a Java project.

This lesson follows the journey step by step, then shows how it looks on your own machine (with scripts, command-line tools, build tools and IDEs).

The journey in four steps

  1. Source code. You write a file ending in .kt, for example main.kt. It is plain text.
  2. Compilation. The Kotlin compiler, kotlinc, reads the text, checks that the syntax and the types make sense, and translates it. On the JVM target the output is bytecode stored in .class files.
  3. Packaging (optional). Class files are usually bundled into a .jar archive, together with the libraries your program needs.
  4. Execution. The Java Virtual Machine (JVM) loads the classes and runs them. Its just-in-time (JIT) compiler turns hot bytecode into fast machine code while the program runs.

Kotlin therefore needs two things on the machine: a compiler to produce the classes (only at build time) and a JVM plus the Kotlin standard library to run them.

On this site the steps run on a server. Your code is compiled by kotlinc into class files, then started with the java command, and the output comes back to the page. It is a real compile, which is why a run takes a few seconds and why compile errors look exactly like those on your computer.

Compile time and run time

Almost every problem in a program belongs to one of two moments.

  • Compile-time errors are found by the compiler before anything runs: misspelled names, wrong types, missing return values. Nothing executes, and you get a message with a line and column.
  • Run-time errors happen while the program is running: dividing by zero, reading a list element that does not exist, a file that is not there. The program starts, prints what it can, then stops with an exception and a stack trace.

Kotlin pushes as many mistakes as possible into the first group, because those are cheaper to fix. See the difference side by side.

Kotlin A compile-time error (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with main.kt:3:20: error: initializer type mismatch: expected 'Int', actual 'String'. and the first println never runs, because no program was produced at all. Now the same kind of slip that only shows up while running:

Kotlin A run-time error (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This one compiles, since the compiler cannot know how many items a list will have. The program prints Before the problem, then fails with Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3 (listOf is backed by a Java array here, so the exception is that subclass) plus a stack trace that names MainKt.main(main.kt:4). The last println is never reached. The runner also notes that the process exited with a non-zero code, which is the convention for "something went wrong".

Read a stack trace from the top: the first line says what happened, the next lines say where, starting with the innermost call. The line number in main.kt:4 points at your code.

What a file turns into: MainKt

On the JVM everything lives inside classes, yet Kotlin lets you write fun main() at the top level. How? The compiler quietly creates a class for each file. A file main.kt becomes a class named MainKt, and every top-level function in it becomes a static method of that class. You can see this from Kotlin itself.

Kotlin The class behind a file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

It prints MainKt. When the JVM starts the program it is told to run MainKt, and it calls the static main method inside. This is also why Kotlin code can be called from Java: a Java program sees MainKt.greet() as an ordinary static method (more in Java Interoperability).

The standard library and default imports

Your program does not run alone. The Kotlin standard library (kotlin-stdlib) is a .jar of ready-made classes and functions: strings, collections, ranges, text and file helpers, println, and much more. It is why listOf and println work without any setup. A handful of packages are imported into every file automatically, among them kotlin.*, kotlin.collections.*, kotlin.text.*, kotlin.io.*, kotlin.ranges.*, kotlin.sequences.* and kotlin.annotation.*. Anything else, including all of the Java library, needs an import.

Kotlin Default imports versus an explicit import

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Because the standard library is itself a normal library, a Kotlin program needs it at run time. That is the one runtime cost of Kotlin compared with Java: a library of well over a megabyte must be on the class path. Build tools add it for you.

Scripts, single files and projects

There are several ways to run Kotlin code on your own machine, from tiny to serious.

1. The compiler on the command line. Install the command-line compiler, then compile and run a file. Everything on this page can be reproduced this way.

Terminal
# read-only example: needs a local Kotlin installation
kotlinc main.kt -include-runtime -d app.jar
java -jar app.jar

-include-runtime copies the standard library into the jar, so java -jar can start it on its own, and -d names the output file.

2. Kotlin scripts. A file ending in .kts is a script: statements can sit at the top level without any main. Scripts are handy for small automation tasks, and they are also what Gradle build files use (build.gradle.kts).

Kotlin
// read-only example: save as hello.kts
val names = listOf("Ada", "Linus")
for (name in names) println("Hello, $name")

3. A project with a build tool. Real applications use Gradle (or Maven). The build file lists the Kotlin version, the libraries to download and the tests to run; the tool then compiles everything in the right order and builds the final package.

Kotlin
// read-only example: build.gradle.kts of a small application
plugins {
    kotlin("jvm") version "2.4.21"
    application
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(kotlin("test"))
}

application {
    mainClass.set("MainKt")
}

You will meet build files again in Gradle Basics for Kotlin and project layout in Project Structure and Modules. Our runner skips this layer: one file, no dependencies besides the standard library and coroutines.

IDEs and tools

You can write Kotlin in any text editor, but an IDE gives you much more: instant error highlighting, auto-completion, safe renaming across files, a debugger, and one-click run.

  • IntelliJ IDEA (Community or Ultimate) is the reference IDE, made by the same company as Kotlin. Start a new project, choose Kotlin and Gradle, and press the green arrow beside main.
  • Android Studio is built on IntelliJ and is the standard tool for Android apps.
  • VS Code works with Kotlin through a language-server extension.
  • Kotlin Notebook and online playgrounds let you try snippets without installing anything, in the same spirit as this site.

A useful IDE feature for learning is Show Kotlin Bytecode, which displays the bytecode of the current file and has a Decompile button that turns it back into Java. Looking at that Java is a great way to see what Kotlin features really do: a data class becomes a class with fields, getters and equals; a top-level function becomes a static method.

Why startup is not instant

Starting a Kotlin/JVM program means starting a JVM, loading classes, and then slowly optimizing hot code while the program runs. Short-lived programs spend a noticeable share of their time on this warm-up, which is why a "hello world" takes a fraction of a second in Kotlin but a few milliseconds in a native language. Long-running servers do not care: the warm-up happens once, and after that the JIT often produces code as fast as hand-tuned native code. If startup time really matters (a command-line tool that is launched thousands of times), look at Kotlin/Native or GraalVM native images.

Kotlin Measuring a small piece of work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The sum is always 500000500000. The time itself would differ on every run, so the program prints only a yes/no answer; never rely on exact timings. Benchmarks need many repetitions and a warm JVM, which is the topic of specialized tools.

Common questions

  • Do I need to install Java? You need a JDK to run Kotlin/JVM programs. IntelliJ IDEA and Gradle can download one for you.
  • Is Kotlin slower than Java? For the same kind of code the performance is the same, because both produce bytecode for the same JVM. Some Kotlin features (lambdas that are not inlined, boxing of nullable numbers) have costs you will learn to recognize.
  • Can the compiler find all bugs? No. It finds type and structure errors, not logic errors. Tests and careful reading are still necessary.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the Kotlin compiler produce for the JVM target?

    kotlinc translates Kotlin source into JVM bytecode. The JVM then executes the bytecode, compiling hot parts to machine code at run time.
  2. 2. What is the generated class called for a top-level function in main.kt?

    The compiler puts the top-level declarations of main.kt into a class called MainKt (file name plus Kt), and top-level functions become its static methods.
  3. 3. Which error is reported before the program starts?

    Type mismatches are compile-time errors, found by the compiler. The other three can only be detected while the program is running.
  4. 4. Which file extension marks a Kotlin script?

    A .kts file is a Kotlin script whose statements can be written at the top level. Build files such as build.gradle.kts are scripts too.
  5. 5. Why does a short Kotlin/JVM program take a moment to start?

    Starting the JVM and loading the standard library takes time. Long-running programs hide this cost, short ones do not.

Summary

  • Kotlin source (.kt) is compiled by kotlinc to JVM bytecode, packaged in jars, and run by the JVM.
  • Compile-time errors stop the build before anything runs; run-time errors are exceptions with stack traces.
  • A file main.kt becomes the class MainKt, and top-level functions become its static methods.
  • The standard library is imported partly by default; the Java library and kotlin.math need explicit imports.
  • You can use the command-line compiler, .kts scripts, or a Gradle project; IntelliJ IDEA is the reference IDE.
  • JVM start-up and warm-up cost time for tiny programs and vanish for long-running ones.

Next: Variables: val and var