Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Wednesday, April 29, 2020

Kotlin Main Function - fun main(args: Array) Examples

1. Introduction


In this article, You'll learn how to create the main() method in kotlin. This is also called a fun main() method.

Kotlin Main Function - fun main() and fun main(args: Array<String>) Examples



2. fun main() Examples - Main Function


the main() method in kotlin can be written in two formats.

[package com.javaprogramto.kotlin.main

fun main() {

print("Hello world")

}]

As you have seen the above code that is the main() method in the kotlin and does not take any arguments and no return type to it.


You have to save this as file extension as file-name.kt. So, kt is the extension of the source file in kotlin.

Create Kotiln's first program and run from Intelleji IDE.

Once you write the code in Intelleji IDE, it detects the main() method automatically and it will show the arrow or play symbol at the main() method line and it will be on the left sidebar.

Once you click on that it will show the options to run and debug the program as well as it shows another option that generates the output with the coverage.

kotin-intelleji-run-program


Here, you can see all the options available in the IntelliJ IDE.

Once you click on the "Run" or "control + shift+ F10", it will show the output on the console.

kotlin-outout-intelleji



It has a printed "Hello World" program.

3. fun main(args: Array<String>) Example - - Main Function


Another way to create the main function in kotlin. In this way, you can pass the string array as in the main() method in java.


main sring array method


[fun main(args: Array<String>) {

println("Hello world with string[] array as argument")

}]

Output:

[Hello world with string[] array as argument]

main sring array output


If you want to pass any values to the main method, you can pass it.

run-configurations-passing arguemnts to main method-min


Provide the values as shown in the above picture and print the arguments from the main method.

[fun main(args: Array<String>) {

println("Hello world with string[] array as argument")
println("argumens : "+Arrays.toString(args))

}]

Output:

[Hello world with string[] array as argument
argumens: [one, two]]

4. Conclusion


In conclusion, You've learned how to create the main function or main method in two ways. The first way is without passing any argument and second is passing String[] array arguments.

Both will work in all scenarios.

[View on GitHub ##eye##]

[Download ##file-download##]

Kotlin Main Function

No comments:

Post a Comment

Please do not add any spam links in the comments section.