Your First Kotlin Program
In this page:
The main() Function
Every runnable Kotlin program needs an entry point function called main, marked with the fun keyword. When you run the compiled program, execution starts at the first line inside main's curly braces.
Example: The main() Function
fun main() {
println("Hello from main()")
}
Login to try C/C++/Java/PHP code in the editor
Printing Hello, World
The classic first program in any language prints a greeting to the screen. In Kotlin, println("Hello, World!") does exactly that, sending the text to standard output followed by a newline.
Note: println adds a newline after the text; print does not.
Example: Printing Hello, World
fun main() {
println("Hello, World!")
}
Login to try C/C++/Java/PHP code in the editor
Understanding the Syntax
Curly braces { } mark the start and end of the function body, and each statement inside typically sits on its own line. Unlike some languages, Kotlin does not require a semicolon at the end of each line.
Example: Understanding the Syntax
fun main() {
println("Curly braces group statements together")
println("No semicolon needed at the end of a line")
}
Login to try C/C++/Java/PHP code in the editor
Compiling and Running
Save the code in a file such as Hello.kt, then compile it with kotlinc Hello.kt -include-runtime -d hello.jar and run the result with java -jar hello.jar to see the output printed in your terminal.
Example: Compiling and Running
fun main() {
println("Saved as Hello.kt, compiled, then run")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the
funkeyword beforemain, which is required to define any function in Kotlin. - Misspelling
printlnasprint_lnorPrintln, causing a compiler error since Kotlin is case-sensitive. - Leaving off the closing
}for themainfunction body and getting a confusing 'expecting a top level declaration' error.
- Every standalone Kotlin program needs a
fun main()function as its entry point. println()prints text followed by a newline; text must be wrapped in double quotes as a string.- Kotlin is case-sensitive, so
Main,main, andMAINare three different identifiers. - Kotlin source files typically end in
.ktand are compiled withkotlinc.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: