Kotlin Hello World

In this tutorial, you will learn how to write and run hello world program in Kotlin. Let's see how you can achieve this by following the procedures mentioned below

Requirement of Kotlin Hello World Example

For running any program written in Kotlin, you need the following-

  1. Install the latest version of JDK from Oracle.
  2. Download zip file of Kotlin compiler from Github using this link.
    Once you have downloaded the zip file, unzip it into a folder. And add the bin folder to the system path.

Example of Hello World in Kotlin

fun main(args: Array<String>){
   println("My First Kotlin program")


My First Kotlin Program

Save this file as hello.kt. Remember one thing the file extension of a program written in Kotlin is .kt or .kts.

To compile a program- kotlinc sourcefile.kt -include-runtime -d jarfile.jar
So to compile the above code, you run- kotlinc hello.kt -include-runtime -d hello.jar

To execute- java -jar hello.jar

Output of Hello World Program

Note- kotlinc is the Kotlin compiler. -include-runtime option makes jarfile.jar file runnable by including Kotlin runtime library in it. The -d option indicates in what form the output of the compiler to be called.

Explanation of above program

In every Kotlin program, the main function is necessary. It is similar to public static void main(String args[]) function in Java. It takes an array of string as an argument and returns nothing.

The println() function is used to display the provided message on the output stream. It is similar to System.out.println() function in Java.

Build Process of Kotlin

Following diagram explains the build process of Kotlin-

Kotlin build process

You store the source code written in Kotlin in a file having extension .kt. When you run kotlinc command, Kotlin compiler generates .class files similar to the Java compiler. The generated .class files are packaged into .jar file. And using java or kotlin command you execute your code.

To compile, run the below command

kotlinc sourcefile.kt -include-runtime -d jarfile.jar

To execute, run the below commands

java -jar jarfile.jar