Kotlin If...Else

Making decisions in your Kotlin programs

🤔 What is If...Else?

If...Else statements allow your program to make decisions based on conditions. They execute different code blocks depending on whether a condition is true or false, making your programs smart and interactive.


// Simple if statement
val age = 18
if (age >= 18) {
    println("You are an adult!")
}
                                    

Types of If Statements

Simple If

Execute code when condition is true

if (score > 90) {
    println("Excellent!")
}
⚖️

If...Else

Choose between two options

if (weather == "sunny") {
    println("Go outside!")
} else {
    println("Stay inside!")
}
🔗

Else If

Multiple conditions to check

if (grade >= 90) {
    println("A")
} else if (grade >= 80) {
    println("B")
} else {
    println("C")
}
📝

If Expression

Return values from if statements

val result = if (x > 0) {
    "positive"
} else {
    "negative"
}

🔹 Basic If Statement

The simplest form checks one condition:

fun main() {
    val temperature = 25
    
    if (temperature > 20) {
        println("It's warm today!")
    }
    
    println("Program continues...")
}

Output:

It's warm today!

Program continues...

🔹 If...Else Statement

Choose between two different actions:

fun main() {
    val password = "secret123"
    
    if (password == "secret123") {
        println("Access granted!")
    } else {
        println("Access denied!")
    }
}

Output:

Access granted!

🔹 Multiple Conditions (Else If)

Check several conditions in sequence:

fun main() {
    val score = 85
    
    if (score >= 90) {
        println("Grade: A - Excellent!")
    } else if (score >= 80) {
        println("Grade: B - Good job!")
    } else if (score >= 70) {
        println("Grade: C - Not bad!")
    } else {
        println("Grade: F - Study harder!")
    }
}

Output:

Grade: B - Good job!

🔹 If as Expression

In Kotlin, if can return a value:

fun main() {
    val age = 16
    
    val status = if (age >= 18) {
        "Adult"
    } else {
        "Minor"
    }
    
    println("Status: $status")
    
    // Short form
    val message = if (age >= 18) "Can vote" else "Cannot vote"
    println(message)
}

Output:

Status: Minor

Cannot vote

🔹 Logical Operators

Combine multiple conditions:

fun main() {
    val age = 25
    val hasLicense = true
    
    // AND operator (&&)
    if (age >= 18 && hasLicense) {
        println("Can drive!")
    }
    
    // OR operator (||)
    val day = "Saturday"
    if (day == "Saturday" || day == "Sunday") {
        println("It's weekend!")
    }
    
    // NOT operator (!)
    val isRaining = false
    if (!isRaining) {
        println("Good weather for a walk!")
    }
}

Output:

Can drive!

It's weekend!

Good weather for a walk!

🧠 Test Your Knowledge

What will this code print?
val x = 10; if (x > 5) println("Big") else println("Small")