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
For running any program written in Kotlin, you need the following-
fun main(args: Array<String>){ println("My First Kotlin program") }
Output
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
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.
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.
Following diagram explains the build process of Kotlin-
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