Your First Kotlin Program
Your First Kotlin Program
Hello, World!â
Every programming journey begins with a simple "Hello, World!" program. In Kotlin, it takes just two lines.
fun main() {
println("Hello, World!")
}
Output:
Hello, World!
Breaking It Downâ
funâ
The fun keyword is used to declare a function in Kotlin.
main()â
main is the entry point of every Kotlin program. When you run your program, Kotlin starts execution from the main function.
println()â
println stands for "print line." It prints the given text to the console followed by a newline character.
Variations of the Main Functionâ
// Basic main function
fun main() {
println("Hello!")
}
// Main with command-line arguments
fun main(args: Array<String>) {
println("Arguments: ${args.size}")
}
Print vs Printlnâ
fun main() {
print("Hello, ") // Does NOT move to next line
print("World!") // Continues on the same line
println() // Prints a blank new line
println("Kotlin!") // Prints and moves to next line
}
Output:
Hello, World!
Kotlin!
Printing Variablesâ
fun main() {
val name = "Kotlin"
val version = 2.0
println("Language: $name")
println("Version: $version")
println("Welcome to $name $version!")
}
Output:
Language: Kotlin
Version: 2.0
Welcome to Kotlin 2.0!
String Templatesâ
Kotlin supports string templates using $ for variables and ${} for expressions:
fun main() {
val a = 10
val b = 20
println("Sum of $a and $b is ${a + b}")
}
Output:
Sum of 10 and 20 is 30
Comments in Kotlinâ
fun main() {
// This is a single-line comment
/*
* This is a
* multi-line comment
*/
println("Comments don't affect output") // inline comment
}
Your First Complete Programâ
fun main() {
// Greet the user
val language = "Kotlin"
val year = 2024
println("============================")
println(" Welcome to $language!")
println(" Year: $year")
println("============================")
}
Output:
============================
Welcome to Kotlin!
Year: 2024
============================
Common Mistakes to Avoidâ
| Mistake | Wrong | Correct |
|---|---|---|
| Missing parentheses | println "Hello" | println("Hello") |
| Wrong function keyword | function main() | fun main() |
| Case sensitivity | Main() | main() |
| Missing quotes | println(Hello) | println("Hello") |
Summaryâ
- Use
fun main()as the program entry point. - Use
println()to print output with a new line. - Use
print()to print without moving to the next line. - Use
$variableor${expression}inside strings for templates. - Comments use
//for single-line and/* */for multi-line.
Telemetry Integration
Completed working through this block? Sync progress to workspace.