The "Hello World" program is the traditional first program when learning a new language. This guide shows you how to write, compile, and run a Kotlin program from the command line.
Writing Your First Kotlin Program
Step 1: Create a new file named hello.kt using any text editor (Notepad++, VS Code, Sublime Text, etc.)
Step 2: Add the following code:
fun main() {
println("Hello, World!")
}
Understanding the Code
-
fun main: Entry point of the Kotlin application -
println: Built-in function to print output to console - No semicolons required (optional in Kotlin)
-
.ktextension is used for all Kotlin source files
Compiling the Program
Step 1: Open terminal/command prompt and navigate to the directory containing hello.kt
cd path/to/your/file
Step 2: Compile the Kotlin file to a JAR:
kotlinc hello.kt -include-runtime -d hello.jar
Explanation of flags:
-
kotlinc: Kotlin compiler command -
-include-runtime: Packages Kotlin runtime library in the JAR -
-d hello.jar: Output file name (destination)
Compilation Output
If successful, you'll see a hello.jar file created in the same directory. No output means compilation succeeded.
Common Compilation Errors
Error: "kotlinc is not recognized"
- Solution: Kotlin compiler is not in PATH. Verify installation.
Error: Syntax errors
- Check for typos in function name or missing braces
- Ensure proper code structure
Running the Program
Execute the compiled JAR file:
java -jar hello.jar
Expected Output:
Hello, World!
Alternative: Direct Execution (Kotlin Script)
You can also run Kotlin code directly without creating a JAR:
Create hello.kts (Kotlin Script):
println("Hello, World!")
Run directly:
kotlinc -script hello.kts
This is useful for quick testing and scripting.
Complete Workflow Summary
| Step | Command | Description |
|---|---|---|
| 1. Write | Create hello.kt |
Write Kotlin source code |
| 2. Compile | kotlinc hello.kt -include-runtime -d hello.jar |
Compile to executable JAR |
| 3. Run | java -jar hello.jar |
Execute the program |
Enhanced Example: Custom Message
Let's create a more interactive program:
fun main() {
val name = "Kotlin"
println("Hello, $name!")
println("Welcome to Kotlin programming.")
println("Current year: ${2024}")
}
Output:
Hello, Kotlin!
Welcome to Kotlin programming.
Current year: 2024
Tips for Command Line Development
- First compilation is slow: JVM warmup takes time
- Use Kotlin daemon: Faster subsequent compilations
- Clean build: Delete old JAR files before recompiling
- Check version: Verify Kotlin version with
kotlinc -version
kotlinc -daemon hello.kt
Next Steps
- Learn about Kotlin program structure and concepts
- Set up an IDE for better development experience
- Explore variables, data types, and functions