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:
java -versionCheck 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:
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:
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:
mkdir -p ~/hello-kotlin-demo
cd ~/hello-kotlin-demo
cat > hello.kt <<'KT'
fun main() {
println("Hello, world!")
}
KTYou 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 calledmain.funis the keyword for every function.mainis where the program starts, and it can sit at the top level of a file, outside any class. You can writefun 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.printlncomes 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:
kotlinc hello.kt -include-runtime -d hello.jar
ls -lh hello.jar
java -jar hello.jarThe compile takes several seconds the first time, for the same JVM start-up reason. What each part does:
kotlinc hello.ktcompiles your source file to JVM bytecode.-d hello.jarnames the output. Because it ends in.jar, the compiler writes a JAR with a manifest that names yourmainas the start point. With a folder name instead, it writes loose.classfiles.-include-runtimecopies the Kotlin standard library into the JAR. Almost every real program calls into that library (greet.ktin the next step does, throughreadlnOrNullandtrim), 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:
unzip -l hello.jar | grep HelloKt
javap -cp hello.jar HelloKtThe 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:
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.jarLine by line:
import java.time.LocalDateimports 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.valdeclares a value that cannot be reassigned. The typeString?, with a question mark, means "a String or null".readlnOrNull()returnsnullwhen 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. Ifinputis null, the whole expression is null andtrim()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.itis 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, sonamehas the typeString, without a question mark."Hello, $name!"is a string template:$nameputs the value ofnameinto 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:
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:
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:
cat > broken.kt <<'KT'
fun main() {
val input: String? = readlnOrNull()
println("Your name has ${input.length} characters.")
}
KTCompile it:
kotlinc broken.kt -d broken.jarThe 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: thebinfolder is not on your path in this terminal. Open a new terminal so~/.bashrcruns, or run theexport PATH=...line again.no main manifest attribute, in hello.jar: the JAR has no start class recorded, usually because the file has nomainfunction. Check the spelling offun main();fun Main()is a different function.Exception in thread "main" java.lang.NoClassDefFoundErrornaming akotlin/...class (such askotlin/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 Hellowhen you run compiled classes by hand withjava -cp: the class isHelloKt, named after the file, notHello.Val cannot be reassigned: you declared something withvaland then gave it a new value. Usevarwhen a value really has to change, and keepvalas your default.
Clean up when you are done. This removes only the folder you made:
rm -rf ~/hello-kotlin-demoKeep 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
- See the same JVM model from the Java side, with
javac, class files and JARs: Hello World in Java. - Compare Kotlin with the language used for Apple platforms: Hello World in Swift.
- Try the language behind Flutter, the other common choice for Android apps: Hello World in Dart.
Related tutorials
- Hello World in Java: compile with javac and run on the JVMYou will install the Eclipse Temurin JDK 25, compile and run a classic Java Hello World, run the shorter Java 25 form straight from source, and package a greeting program as a runnable JAR.
- Hello World in Swift on Linux, macOS and Windows with the Swift package managerYou will install Swift 6.4 with swiftly, run a one-line script, create and run an executable package with swift run, and greet the reader by name using an optional from readLine().
- Hello World in Dart: dart create, dart run and a compiled executableYou will install Dart 3.14, create a console app with dart create, run it with dart run, compile it to a native executable, compare start-up times and greet a name from the command line with null-safe code.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials