Kotlin - First Program
Your First Kotlin Program
Let's write, understand, and run your first Kotlin program step by step. We'll start simple and gradually explore the language features.
Hello, World!
Every programming journey begins with "Hello, World!" - here's the Kotlin version:
fun main() {
println("Hello, World!")
}
Breaking It Down
fun
- Kotlin keyword to declare a functionmain
- The name of the function; program entry point()
- Empty parentheses mean no parameters{}
- Curly braces contain the function bodyprintln
- Built-in function to print a line"Hello, World!"
- String literal to display
Beginner Note: Unlike Java, Kotlin doesn't require a class for simple programs. The
main
function can exist on its own, making code more concise for beginners.
Running Your Program
Method 1: Command Line
- Create a file named
Hello.kt
- Add the code above
- Compile and run:
# Compile to JAR
kotlinc Hello.kt -include-runtime -d Hello.jar
# Run the program
java -jar Hello.jar
Method 2: Direct Script Execution
# Compile and run in one step
kotlinc -script Hello.kt
Method 3: Using IDE
- Create a new Kotlin project in IntelliJ IDEA
- Replace the default code with our Hello World
- Click the green "Run" arrow or press Ctrl+Shift+F10
Understanding Program Structure
Traditional Java vs Kotlin
Java
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Kotlin
fun main() {
println("Hello, World!")
}
Kotlin Advantages:
- No need for a class wrapper
- No public/static keywords required
- Shorter println function
- Less ceremony, more focus on logic
Expanding the Program
Adding Variables
fun main() {
val name = "Kotlin"
val version = 1.9
println("Hello, $name $version!")
}
Understanding String Templates
The $
symbol allows you to embed variables directly in strings:
fun main() {
val language = "Kotlin"
val year = 2023
println("I'm learning $language in $year")
println("${language.length} letters in the name")
}
Teacher Note: String templates are a great way to introduce variables and expressions early. They're more intuitive than string concatenation for beginners.
Multiple Statements
fun main() {
println("Welcome to Kotlin!")
println("This is line 2")
println("This is line 3")
val greeting = "Hello"
val name = "Developer"
println("$greeting, $name!")
}
Interactive Examples
Calculator Example
fun main() {
val a = 10
val b = 5
println("$a + $b = ${a + b}")
println("$a - $b = ${a - b}")
println("$a * $b = ${a * b}")
println("$a / $b = ${a / b}")
}
Personal Information
fun main() {
val firstName = "John"
val lastName = "Doe"
val age = 25
val city = "New York"
println("Personal Information:")
println("Name: $firstName $lastName")
println("Age: $age years old")
println("City: $city")
println("Full info: $firstName $lastName, $age, from $city")
}
Fun with Numbers
fun main() {
val number = 42
println("The number is: $number")
println("Double the number: ${number * 2}")
println("Square of the number: ${number * number}")
println("Is it even? ${number % 2 == 0}")
}
Common Beginner Mistakes
❌ Incorrect
// Missing fun keyword
main() {
println("Hello")
}
// Wrong file extension
// Save as Hello.java instead of Hello.kt
// Incorrect string syntax
fun main() {
println('Hello, World!') // Single quotes for strings
}
✅ Correct
// Proper function declaration
fun main() {
println("Hello, World!")
}
// Save as Hello.kt
// Use double quotes for strings
Program Variations
With Command Line Arguments
fun main(args: Array<String>) {
if (args.isNotEmpty()) {
println("Hello, ${args[0]}!")
} else {
println("Hello, World!")
}
}
Run with: java -jar Hello.jar YourName
Multiple Functions
fun main() {
greet("Kotlin")
showMath(10, 5)
}
fun greet(name: String) {
println("Hello, $name!")
}
fun showMath(a: Int, b: Int) {
println("$a + $b = ${a + b}")
}
Architecture Note: Even in simple programs, separating concerns into functions promotes good design. This becomes crucial as applications grow in complexity.
Exploring Further
Comments in Code
fun main() {
// Single line comment
println("Hello, World!")
/*
* Multi-line comment
* Can span multiple lines
*/
val name = "Kotlin" // Comment at end of line
println("Learning $name")
}
Different Data Types
fun main() {
val text = "Hello" // String
val number = 42 // Int
val decimal = 3.14 // Double
val isTrue = true // Boolean
val letter = 'K' // Char
println("Text: $text")
println("Number: $number")
println("Decimal: $decimal")
println("Boolean: $isTrue")
println("Character: $letter")
}
Project Structure
Simple Project Layout
my-kotlin-project/
├── src/
│ └── main/
│ └── kotlin/
│ └── Main.kt
├── build.gradle.kts (if using Gradle)
└── README.md
Package Declaration
package com.example.myapp
fun main() {
println("Hello from package!")
}
Beginner Note: Packages help organize code as projects grow. They're like folders for your code files. Start simple and add packages as needed.
Best Practices for Beginners
- Start Small: Begin with simple programs like Hello World
- Use Meaningful Names:
userName
instead ofx
- Add Comments: Explain what your code does
- One Concept at a Time: Don't try to learn everything at once
- Practice Regularly: Write code every day, even if it's small
- Experiment: Change values and see what happens
Try it Yourself
- Create and run the basic Hello World program
- Modify it to display your name: "Hello, [Your Name]!"
- Add variables for your age and city, then display them
- Create a simple calculator that adds two numbers
- Experiment with different data types (text, numbers, true/false)
Challenge Exercises
- Write a program that displays a simple ASCII art pattern
- Create a program that calculates the area of a rectangle
- Make a program that displays today's date and time (hint: use System.currentTimeMillis())
Quick Quiz
- What keyword is used to declare a function in Kotlin?
- What symbol is used for string templates in Kotlin?
- Do you need a class to write a simple Kotlin program?
- What file extension should Kotlin files have?
Show answers
fun
$
(dollar sign)- No, you can have a standalone main function
.kt