Skip to main content

Hello World (first programs) · Beginner · 14 min

Hello World in Kotlin: kotlinc, a runnable JAR and null safety

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Kotlin 2.4.21 · Eclipse Temurin JDK 25

You will install the Kotlin 2.4 command-line compiler, build Hello World into a self-contained JAR that runs with java -jar, and extend it to read a name safely when no input arrives.

On this page

Kotlin is a statically typed language from JetBrains that compiles to the same JVM bytecode as Java. A Kotlin program and a Java program end up as .class files in a JAR, run by the same java command, and they can call each other's code directly. Kotlin was built to keep that compatibility while removing a lot of Java's ceremony, and to catch one of the most common crashes in Java programs, the NullPointerException, when you compile rather than when your users run the program.

In this tutorial you install kotlinc, the Kotlin command-line compiler, from the official release. You write Hello World, compile it into a JAR that carries the Kotlin standard library inside it, and run it with plain java -jar. Then you go one step further: you read a name from the keyboard and handle the case where nothing arrives, which is where Kotlin's null safety shows up on day one.

Real Kotlin projects usually start in Gradle or Android Studio, which run the compiler for you. Using kotlinc by hand first shows you what those tools do underneath.

Step 1 · Check that JDK 25 is installed

kotlinc is itself a JVM program, and the JARs it builds need a JVM to run, so you need a JDK first. If you do not have one, follow the first step of Hello World in Java, which installs Eclipse Temurin JDK 25 from the Adoptium apt repository. Then check it:

Bash
java -version

Check it worked

The first line starts with something like openjdk version "25.0.5". Any JDK 25 patch release works. If you see command not found, install the JDK before going on.

Step 2 · Install the Kotlin compiler

JetBrains publishes the compiler as one zip file on the Kotlin GitHub releases page, with a SHA-256 checksum beside it. The zip is about 90 MB, so if you are on prepaid mobile data, download it over Wi-Fi. Install curl and unzip, download both files into a fresh temporary folder, and check the zip against the checksum:

Bash
sudo apt update
sudo apt install -y curl unzip ca-certificates
KOTLIN_VERSION=2.4.21
cd "$(mktemp -d)"
curl -fsSLO "https://github.com/JetBrains/kotlin/releases/download/v${KOTLIN_VERSION}/kotlin-compiler-${KOTLIN_VERSION}.zip"
curl -fsSLO "https://github.com/JetBrains/kotlin/releases/download/v${KOTLIN_VERSION}/kotlin-compiler-${KOTLIN_VERSION}.zip.sha256"
echo "$(cat "kotlin-compiler-${KOTLIN_VERSION}.zip.sha256")  kotlin-compiler-${KOTLIN_VERSION}.zip" | sha256sum -c -

The .sha256 file holds only the hash, so the echo line adds the file name in the format sha256sum -c expects. It must print kotlin-compiler-2.4.21.zip: OK. If it prints FAILED, stop, delete the files and download again.

Now unpack the compiler into a folder in your home directory and put its bin folder on your path:

Bash
mkdir -p ~/.local/opt
unzip -q "kotlin-compiler-${KOTLIN_VERSION}.zip" -d ~/.local/opt/kotlin-${KOTLIN_VERSION}
export PATH="$HOME/.local/opt/kotlin-${KOTLIN_VERSION}/kotlinc/bin:$PATH"
echo "export PATH=\"\$HOME/.local/opt/kotlin-${KOTLIN_VERSION}/kotlinc/bin:\$PATH\"" >> ~/.bashrc
kotlinc -version
rm "kotlin-compiler-${KOTLIN_VERSION}.zip" "kotlin-compiler-${KOTLIN_VERSION}.zip.sha256"

The zip contains a folder called kotlinc, and kotlinc/bin holds the kotlinc and kotlin launch scripts. The export line makes them work in this shell, and the line appended to ~/.bashrc does the same for every new terminal. The last line deletes the downloaded zip and checksum, because the unpacked compiler is all you need. If you want to install on another machine without downloading again, copy the zip somewhere safe, such as ~/Downloads, before you run that line.

A compiler you unpack yourself gets no updates from apt. To upgrade, repeat this step with a newer KOTLIN_VERSION, change the version in the line at the end of ~/.bashrc, and delete the old folder under ~/.local/opt.

Other ways to install exist. SDKMAN, a version manager for JVM tools, installs the same compiler with sdk install kotlin 2.4.21 and lets you switch versions later. On macOS, brew install kotlin works. On Windows, unzip the same file and add its kotlinc\bin folder to your PATH in the system settings.

Check it worked

kotlinc -version prints something like info: kotlinc-jvm 2.4.21 (JRE 25.0.5+...). It can take a few seconds, because a JVM has to start before the compiler does any work.

Step 3 · Write Hello World

Make a throwaway folder and create hello.kt in it:

Bash
mkdir -p ~/hello-kotlin-demo
cd ~/hello-kotlin-demo
cat > hello.kt <<'KT'
fun main() {
    println("Hello, world!")
}
KT

You can also type the three lines into your editor and save them as hello.kt. Compare this with Java, where the same program needs a class and a public static void main(String[] args) method. In Kotlin:

  • fun main() { declares a function called main. fun is the keyword for every function. main is where the program starts, and it can sit at the top level of a file, outside any class. You can write fun main(args: Array<String>) when you want the command-line arguments, but you do not have to.
  • println("Hello, world!") prints the text followed by a line break. println comes from the Kotlin standard library and needs no import. There is no semicolon: Kotlin ends a statement at the end of the line.
  • } closes the function.

Check it worked

cat hello.kt shows the three lines, and the file name ends in .kt.

Step 4 · Compile a self-contained JAR and run it

Compile the file into a JAR:

Bash
kotlinc hello.kt -include-runtime -d hello.jar
ls -lh hello.jar
java -jar hello.jar

The compile takes several seconds the first time, for the same JVM start-up reason. What each part does:

  • kotlinc hello.kt compiles your source file to JVM bytecode.
  • -d hello.jar names the output. Because it ends in .jar, the compiler writes a JAR with a manifest that names your main as the start point. With a folder name instead, it writes loose .class files.
  • -include-runtime copies the Kotlin standard library into the JAR. Almost every real program calls into that library (greet.kt in the next step does, through readlnOrNull and trim), so without it the JAR fails at run time unless the library is supplied separately. With it, the JAR needs nothing but Java.

That is why the JAR is a few megabytes for a three-line program. Most of it is the standard library. Android release builds shrink it with R8, a tool that removes code the app never calls.

Now look inside the JAR. The JVM only runs classes, but you never wrote one:

Bash
unzip -l hello.jar | grep HelloKt
javap -cp hello.jar HelloKt

The compiler put your top-level function into a class named after the file: hello.kt becomes HelloKt. javap, the class viewer that ships with the JDK, shows that the class has a public static main method, exactly what a Java programmer would have written by hand. Java code can call your Kotlin function as HelloKt.main(), and that is how the two languages share a project.

Check it worked

java -jar hello.jar prints Hello, world!. unzip -l lists HelloKt.class, and javap prints public final class HelloKt with a main method inside it.

Step 5 · Read a name and handle the missing case

Now make the program ask for a name. Create greet.kt in the same folder:

Bash
cat > greet.kt <<'KT'
import java.time.LocalDate

fun main() {
    print("What is your name? ")
    val input: String? = readlnOrNull()
    val name: String = input?.trim()?.takeIf { it.isNotEmpty() } ?: "world"
    println("Hello, $name!")
    println("Your name has ${name.length} characters.")
    println("Today is ${LocalDate.now().dayOfWeek}.")
}
KT
kotlinc greet.kt -include-runtime -d greet.jar

Line by line:

  • import java.time.LocalDate imports a class from Java's standard library, not Kotlin's. Kotlin calls Java classes directly, with no wrapper code, so every Java library is available to you.
  • print(...) writes the question without a line break, so the cursor waits on the same line.
  • val input: String? = readlnOrNull() reads one line from the keyboard. val declares a value that cannot be reassigned. The type String?, with a question mark, means "a String or null". readlnOrNull() returns null when there is no input at all, for example when input comes from an empty file or the person presses Ctrl+D.
  • input?.trim() is a safe call. If input is null, the whole expression is null and trim() is never called. If not, it removes spaces at both ends.
  • ?.takeIf { it.isNotEmpty() } keeps the text only if something is left after trimming, and turns an empty answer into null too. it is the value being tested.
  • ?: "world" is the Elvis operator: use the value on the left, or "world" if the left side is null. The result can never be null, so name has the type String, without a question mark.
  • "Hello, $name!" is a string template: $name puts the value of name into the text. For anything longer than a plain name, use braces, as in ${name.length} and ${LocalDate.now().dayOfWeek}.

Run the JAR and type a name when it asks:

Text
java -jar greet.jar
What is your name? Amara
Hello, Amara!
Your name has 5 characters.
Today is THURSDAY.

Your day will differ. Now feed it input from a pipe, then give it no input at all:

Bash
echo "  Amara  " | java -jar greet.jar
java -jar greet.jar < /dev/null

< /dev/null sends an empty input, so readlnOrNull() returns null and the Elvis operator supplies world.

Check it worked

The piped run prints Hello, Amara! and Your name has 5 characters., because trim() removed the spaces. The run with no input prints Hello, world!. Both end with Today is and the day of the week in capitals.

Step 6 · Watch the compiler refuse a null mistake

The point of String? is that the compiler will not let you forget the null case. Write a version that skips it:

Bash
cat > broken.kt <<'KT'
fun main() {
    val input: String? = readlnOrNull()
    println("Your name has ${input.length} characters.")
}
KT

Compile it:

Bash
kotlinc broken.kt -d broken.jar

The build fails before any program exists. In Java, the same mistake compiles, and the program crashes with a NullPointerException only when a null actually turns up, maybe months later on a user's phone. Fix it the way greet.kt does, with ?. and ?:, or with an if (input != null) check, after which the compiler treats input as a plain String inside the if.

There is also !!, as in input!!.length, which tells the compiler "trust me, this is not null" and throws an exception if you are wrong. Avoid it while you are learning.

Check it worked

kotlinc prints an error naming broken.kt and line 3, with a message something like Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'String?', and no broken.jar appears in ls.

Step 7 · Fix the mistakes beginners hit and clean up

These come up early. Each has a known cause:

  • kotlinc: command not found: the bin folder is not on your path in this terminal. Open a new terminal so ~/.bashrc runs, or run the export PATH=... line again.
  • no main manifest attribute, in hello.jar: the JAR has no start class recorded, usually because the file has no main function. Check the spelling of fun main(); fun Main() is a different function.
  • Exception in thread "main" java.lang.NoClassDefFoundError naming a kotlin/... class (such as kotlin/io/ConsoleKt): you probably left out -include-runtime, so the Kotlin standard library is missing from the JAR. The class named depends on which library call the program reaches first. Compile again with the flag.
  • Could not find or load main class Hello when you run compiled classes by hand with java -cp: the class is HelloKt, named after the file, not Hello.
  • Val cannot be reassigned: you declared something with val and then gave it a new value. Use var when a value really has to change, and keep val as your default.

Clean up when you are done. This removes only the folder you made:

Bash
rm -rf ~/hello-kotlin-demo

Keep the compiler if you want to carry on. To remove it, delete ~/.local/opt/kotlin-2.4.21 and the export PATH line you added at the end of ~/.bashrc.

Check it worked

ls ~/hello-kotlin-demo reports that there is no such file or directory, and kotlinc -version still works in a new terminal if you kept the compiler.

Where real projects start

You will rarely call kotlinc by hand after today. For a command-line or server program, install Gradle and run gradle init, choosing an application written in Kotlin. It creates a project with a build script, a test folder and a fixed Kotlin version, and ./gradlew run compiles and runs it. For Android, install Android Studio and start a new project from a template; it sets up Gradle, the Android SDK and Kotlin together.

Where Kotlin is used

Google declared Android development Kotlin-first, so most new Android apps and the current Android documentation use it. That matters across Africa, where Android runs most of the phones in use, many of them low-cost models, and many Android apps built in the region are written in Kotlin. On servers, Kotlin runs with Spring Boot, which supports it alongside Java, and with Ktor, a web framework from JetBrains. Kotlin Multiplatform shares code between Android, iOS, desktop and web. Because it compiles to JVM bytecode, a Kotlin team can keep using any Java library, and an existing Java project can add Kotlin one file at a time.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.