Monday, July 29, 2019

Kotlin Introduction and Examples | Kotlin Hello Example | Kotlin For Loop | Kotlin While Loop | Kotlin Array | Android Kotlin

Updated December 2026: I rewrote this post with more examples, fixed some mistakes in the old code, and finally added the Android part that I promised in 2019.

Dear friends,

In July 2019 I wrote a short introduction to Kotlin here and said the Android part would come in a later post. Well, it took a while! Since then Kotlin became the main language for Android: Google announced Android development as "Kotlin-first" in 2019, and today almost every new Android app is written in it.

So I rewrote this post from the beginning, with more examples and simple explanations. When I read my old version again, I also found a few mistakes in the code (for example I wrote boolean, but in Kotlin it's Boolean with a capital B). They are all fixed now.

What is Kotlin?

Kotlin is a modern, statically typed programming language made by JetBrains, the company behind IntelliJ IDEA and Android Studio. Version 1.0 came out in 2016. It runs on the JVM like Java and works 100% together with Java code, so you can even mix Java and Kotlin files in one project.

Why do developers like it? Less code, fewer crashes from null, and easy background work with coroutines.

Where to write Kotlin

  • In your browser: Kotlin Playground. Nothing to install. Perfect for all the examples in this post.
  • Android Studio: for Android apps (the last example below).
  • IntelliJ IDEA: for normal Kotlin programs.

(In 2019 I also suggested Eclipse with a Kotlin plugin. Please don't use that anymore.)

1- Hello Kotlin

Every Kotlin program starts from main(). No class needed, and no semicolons:

fun main() {
    println("Hello, Kotlin!")
}

For the next examples, put the code inside fun main() { } in the Playground.

2- Variables: val and var

Use val for values that don't change, and var for values that change. My tip: always start with val, and change it to var only when you need to. Kotlin usually knows the type by itself, but you can write it after a colon.

val name = "Manish"          // String, can't change (read-only)
var age = 30                 // Int, can change
age = 31

val pi: Double = 3.14        // you can also write the type yourself
val isDeveloper: Boolean = true
val grade: Char = 'A'
val population: Long = 1_400_000_000L

println("$name is $age")     // Manish is 31

The basic types:

TypeWhat it holdsExample
Intwhole numbers42
Longvery big whole numbers9_000_000_000L
Doubledecimal numbers3.14
Floatdecimal numbers, less exact3.14f
Booleantrue or falsetrue
Charone character'A'
Stringtext"Hello"

3- String templates

Put a $ before a variable to use it inside text. For a calculation, use ${ }:

val name = "Ravi"
val apps = 3

println("$name has $apps apps")                // Ravi has 3 apps
println("Next year: ${apps + 2} apps")         // Next year: 5 apps
println("His name has ${name.length} letters") // His name has 4 letters

4- Null safety

This is my favourite Kotlin feature. A normal variable can never be null. If something can be empty, you add a ? to the type, and then Kotlin forces you to handle it. Goodbye to most NullPointerExceptions!

var city: String? = null     // the ? means: this can be null

println(city?.length)        // null (safe call, no crash)
println(city?.length ?: 0)   // 0 (Elvis operator gives a default)

city = "Mumbai"
println(city.length)         // 6 (Kotlin knows it's not null now)

5- If, else and when

val a = 10
val b = 20

if (a > b) {
    println("a is bigger")
} else {
    println("b is bigger")   // b is bigger
}

val max = if (a > b) a else b   // if can return a value
println("Max is $max")          // Max is 20

when is like switch in Java, but much more flexible. It works with values, ranges and more:

val score = 72

val result = when (score) {
    in 90..100 -> "Excellent"
    in 60..89 -> "Good"
    else -> "Try again"
}
println(result)              // Good

val day = "Sunday"
when (day) {
    "Saturday", "Sunday" -> println("Weekend!")
    else -> println("Working day")
}

6- Loops

The for loop works with ranges. .. includes the last number, until doesn't, step jumps, and downTo counts backwards:

for (i in 1..5) print("$i ")          // 1 2 3 4 5
println()

for (i in 1 until 5) print("$i ")     // 1 2 3 4   (5 is not included)
println()

for (i in 1..10 step 2) print("$i ")  // 1 3 5 7 9
println()

for (i in 5 downTo 1) print("$i ")    // 5 4 3 2 1
println()

while and do-while work like in Java. do-while always runs at least one time:

var count = 1
while (count <= 3) {
    println("Count: $count")     // Count: 1, Count: 2, Count: 3
    count++
}

var number = 10
do {
    println("This runs at least once")
    number++
} while (number < 5)

7- Functions

Functions start with fun. Parameters are written as name: Type, and the return type comes after the brackets. Kotlin also has default values and named arguments, which save you from writing many overloaded functions like in Java:

fun add(a: Int, b: Int): Int {
    return a + b
}

fun multiply(a: Int, b: Int) = a * b     // short version for one line

fun greet(name: String, greeting: String = "Hello") = "$greeting, $name!"

fun main() {
    println(add(2, 3))                                  // 5
    println(multiply(4, 5))                             // 20
    println(greet("Ravi"))                              // Hello, Ravi!
    println(greet("Ravi", "Hi"))                        // Hi, Ravi!
    println(greet(greeting = "Welcome", name = "Anna")) // Welcome, Anna!
}

8- Arrays and lists

An array has a fixed size. You read and change items with [ ], which is the same as get() and set():

val numbers = arrayOf(10, 20, 30)
numbers[1] = 25                  // same as numbers.set(1, 25)
println(numbers[1])              // 25, same as numbers.get(1)
println(numbers.size)            // 3

In real apps we mostly use lists. listOf makes a read-only list, and mutableListOf a list you can change. (In my old post I mixed these two up, sorry!) Lists also have useful functions like filter and map:

val countries = listOf("India", "Japan", "Brazil")   // read-only list
for (country in countries) {
    println(country)
}

val cities = mutableListOf("Delhi")                   // list you can change
cities.add("Tokyo")
println(cities)                                       // [Delhi, Tokyo]

val evens = (1..10).filter { it % 2 == 0 }
val squares = evens.map { it * it }
println(evens)                   // [2, 4, 6, 8, 10]
println(squares)                 // [4, 16, 36, 64, 100]

it is the default name for the item inside { }.

9- Classes and data classes

You can write the properties directly in the class header. And a data class gets toString(), equals() and copy() for free. In Java, this would be many lines of code.

class Person(val name: String, var age: Int) {
    fun introduce() = "Hi, I'm $name and I'm $age years old."
}

data class Book(val title: String, val year: Int)

fun main() {
    val person = Person("Ravi", 28)
    println(person.introduce())    // Hi, I'm Ravi and I'm 28 years old.
    person.age = 29

    val book = Book("Kotlin Basics", 2026)
    println(book)                  // Book(title=Kotlin Basics, year=2026)
    println(book.copy(year = 2027))              // Book(title=Kotlin Basics, year=2027)
    println(book == Book("Kotlin Basics", 2026)) // true
}

10- Comments

// This is a single-line comment

/* This is a
   multi-line comment */

Kotlin vs Java, in short

JavaKotlin
Semicolonsneedednot needed
Null safetyNullPointerException at runtimechecked by the compiler
Data classfields, getters, equals, hashCode, toString… many linesone line: data class
Text with values"Hi " + name"Hi $name"
Background workthreads, callbackscoroutines
Works with Java code-yes, 100%, in the same project

11- Finally: Kotlin in an Android app

Here is the Android part I promised in 2019. Create a new project in Android Studio with the Empty Activity template and replace MainActivity.kt with this. It's a small click counter, built with Jetpack Compose:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                CounterScreen()
            }
        }
    }
}

@Composable
fun CounterScreen() {
    var count by rememberSaveable { mutableStateOf(0) }

    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = "You clicked $count times",
            style = MaterialTheme.typography.headlineSmall
        )
        Spacer(Modifier.height(16.dp))
        Button(onClick = { count++ }) {
            Text("Click me")
        }
    }
}

If some names are red, click on them and press Alt + Enter to add the imports. rememberSaveable keeps the number even when you rotate the phone.

That's all for the basics! If you want to go further, see my Android interview questions (with Kotlin, coroutines and Compose), or the Start here page.

Let me know if you need more help. Thanks!

Updated December 2026. Examples written for Kotlin 2.x.