Beginner

Hello World in Kotlin

Your first Kotlin program - the classic Hello World example with Docker setup

Every programming journey starts with Hello World. Let’s write our first Kotlin program.

The Code

Create a file named Hello.kt:

1
2
3
fun main() {
    println("Hello, World!")
}

Understanding the Code

  • fun main() - The entry point of a Kotlin program. fun declares a function. Unlike Java, no class wrapper is required.
  • println() - Prints to standard output with a newline. It’s a top-level function, not System.out.println().
  • No semicolons - Kotlin doesn’t require semicolons at the end of statements.

Running with Docker

The easiest way to run this without installing Kotlin locally:

1
2
3
4
5
# Pull the Kotlin image
docker pull zenika/kotlin:1.4

# Compile and run
docker run --rm -v $(pwd):/app -w /app zenika/kotlin:1.4 sh -c "kotlinc Hello.kt -include-runtime -d hello.jar && java -jar hello.jar"

Running Locally

If you have Kotlin installed:

1
2
3
4
5
# Compile to JAR (includes Kotlin runtime)
kotlinc Hello.kt -include-runtime -d hello.jar

# Run
java -jar hello.jar

Or run directly with the Kotlin script runner:

1
2
# Run as a script (slower startup, good for quick tests)
kotlin Hello.kt

Expected Output

Hello, World!

Key Concepts

  1. Top-level functions - main() doesn’t need to be inside a class
  2. No semicolons - Line breaks typically end statements
  3. fun keyword - Declares functions (like def in Python)
  4. JVM-based - Compiles to Java bytecode, runs on the JVM
  5. Concise syntax - Much less boilerplate than Java

Kotlin vs. Java Hello World

Java version:

1
2
3
4
5
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Kotlin version:

1
2
3
fun main() {
    println("Hello, World!")
}

Kotlin eliminates:

  • The class wrapper requirement
  • The public keyword (it’s the default)
  • The String[] args parameter (optional in Kotlin)
  • System.out. prefix

A Slightly More Complex Example

1
2
3
4
fun main() {
    val name = "World"
    println("Hello, $name!")
}

This demonstrates:

  • val - Immutable variable (like final in Java)
  • String templates - $name embeds variables directly in strings

You can also use expressions in templates:

1
2
3
4
fun main() {
    val name = "Kotlin"
    println("Hello, ${name.uppercase()}!")  // Prints: Hello, KOTLIN!
}

Next Steps

Continue to Variables and Data Types to learn about Kotlin’s type system and null safety.

Running Today

All examples can be run using Docker:

docker pull zenika/kotlin:1.4
Last updated: