Skip to content

Beginner: Kotlin · Kotlin basics · topic 2 of 50 · 30 min

First program, val and var, and types

Explanation

Every Kotlin program starts in fun main(). println prints a line. val creates a read-only variable and var creates one you can change; prefer val. Kotlin works out types like Int, Double, Boolean and String for you, and string templates put values into text with $name and ${expression}.

Your first program

kotlin
fun main() {
    println("Namaste, Kotlin!")
}
fun declares a function; main is where the program starts. println prints and moves to a new line.

fun is short for function, a named block of code. The curly braces hold its body. Unlike Java, you do not need a class or semicolons. Text in double quotes is a String.

val and var

A variable is a name for a value. Kotlin has two kinds. val (value) is read-only: once given a value, it cannot be reassigned. var (variable) can be reassigned. Professional Kotlin code uses val by default and var only when a value really changes, because values that never change make programs easier to understand.

kotlin
fun main() {
    val city = "Surat"
    var visitors = 120
    visitors = visitors + 30      // fine: var can change
    // city = "Vadodara"          // error: Val cannot be reassigned
    println(city)
    println(visitors)             // 150
}
The compiler stops you from changing a val.
Think of it like this: A val is like your date of birth on your Aadhaar card: set once, never changed. A var is like your phone's battery percentage: it keeps changing, and everyone expects it to.

Basic types

TypeHoldsExample
IntWhole numbers (about -2.1 billion to 2.1 billion)val seats = 72
LongBigger whole numbersval population = 1_400_000_000L
DoubleDecimal numbersval price = 99.5
Booleantrue or falseval isOpen = true
CharOne character in single quotesval grade = 'A'
StringText in double quotesval name = "Ravi"

Kotlin uses type inference: it works out the type from the value, so val seats = 72 is an Int. You can also write the type yourself after a colon: val seats: Int = 72. Once a variable has a type, it keeps it; you cannot later put text into an Int variable.

Numbers and division

kotlin
fun main() {
    println(7 / 2)       // 3: Int divided by Int gives an Int (the decimal part is dropped)
    println(7 % 2)       // 1: the remainder
    println(7 / 2.0)     // 3.5: one Double makes the result a Double
    println(7.toDouble() / 2)   // 3.5
}
Integer division drops the decimal part. Convert to Double when you need decimals.

String templates

A string template puts a value inside text. Write $name for a simple variable and ${ } around any expression. This is easier to read than joining text with +.

kotlin
fun main() {
    val item = "Masala dosa"
    val price = 80
    val qty = 3
    println("$item x $qty = Rs ${price * qty}")
    println("Name has ${item.length} characters")
}
Prints: Masala dosa x 3 = Rs 240, then Name has 11 characters.

Converting text to numbers

kotlin
fun main() {
    val typed = "42"
    val n = typed.toInt()           // 42
    val bad = "4two".toIntOrNull()  // null: not a number
    println(n + 1)
    println(bad)
}
toInt() crashes on bad text; toIntOrNull() returns null instead, which is safer for user input.

Comments

A comment is a note for humans that the compiler ignores. // starts a one-line comment; /* ... */ wraps several lines. Use comments to explain why, not to repeat what the code obviously does.

Common mistakes

  • Using var everywhere. Start with val; change to var only if the compiler says the value is reassigned.
  • Expecting 7 / 2 to be 3.5. Integer division gives 3; use 7 / 2.0.
  • Writing "Total: " + price + qty and getting "Total: 803" instead of 83. Use a template: "Total: ${price + qty}".
  • Using toInt() on user input. One bad character crashes the app; use toIntOrNull().

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

First program, val and var, and types · 1/6

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

Every Kotlin program starts in fun main. println prints a line.

Prefer a video by a teacher? Find free videos on “kotlin basics val var types string templates tutorial” on YouTube ↗

In real life: A chai stall bill

A chai stall owner wants a quick calculation: cups sold and price per cup give the day's income. val is used for the fixed price, var for the running count that changes through the day, and a string template prints a clean summary.

kotlin
fun main() {
    val pricePerCup = 12
    var cups = 0
    cups += 85      // morning
    cups += 120     // evening
    println("Cups: $cups, income: Rs ${cups * pricePerCup}")
}
Prints: Cups: 205, income: Rs 2460

Practice (0/3 done)

Task 1 · Question

What does this print? fun main() { val a = 10 val b = 4 println("${a / b} ${a % b}") }

Task 2 · Question

Which line does NOT compile?

Task 3 · Practice

In the Kotlin Playground, write a program for a phone recharge: a val for the plan price (299), a var for the wallet balance (500), subtract the price, and print "Balance after recharge: Rs X" with a string template. Then convert the text "149" to an Int and the text "abc" with toIntOrNull and print both.

Quick quiz

Question 1

1.Which keyword makes a read-only variable?

Question 2

2.What is the type of val price = 49.99?

Question 3

3.What does println(9 / 2) print?

Question 4

4.What does "abc".toIntOrNull() return?

Question 5

5.How do you put an expression inside a string?

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which keyword makes a read-only variable?

Answer: val

val values cannot be reassigned.

What is the type of val price = 49.99?

Answer: Double

Decimal literals are Double by default.

What does println(9 / 2) print?

Answer: 4

Int / Int is integer division.

What does "abc".toIntOrNull() return?

Answer: null

It returns null when the text is not a number.

How do you put an expression inside a string?

Answer: "Total: ${a + b}"

${ } evaluates the expression in a string template.

Which inserts an expression into a string?Related

Answer: 'Total: ${a + b}'

${...} evaluates the expression.

From Your first Dart program, variables and types

Which Kotlin feature replaces Java's switch statement?Related

Answer: when

when is Kotlin's flexible branching construct.

From Conditions: if and when

Which Kotlin feature should you avoid because it can throw a NullPointerException?Related

Answer: !!

!! asserts non-null.

From Interview questions: Kotlin

What is wrong with: var x;Related

Answer: var needs a value on the same line so the compiler can infer the type

The compiler infers the type from the value, so var must be initialised.

From Types and variables

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Kotlin basics” before its exam: Conditions: if and when, Loops and ranges.
  2. Module 1 exam: Kotlin basics · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Null safety, functions and lambdas. 50 topics left in the course before the final exam.

← Previous: Kotlin and Android: the big picture