Control Flow in Kotlin: If-Else

1. Why Use If-Else?

Control flow statements allow a program to make decisions and execute different code paths based on conditions. In Kotlin, if and if-else statements are used to:

2. How to Use If-Else? (With Example)

The if statement evaluates a condition and executes code if the condition is true. You can add else to handle the false case.

fun main() {
    val number = 10

    if (number > 0) {
        println("Number is positive")
    } else {
        println("Number is zero or negative")
    }
}

Output:

Number is positive

3. Explain Each Form

3.1 Simple If

Executes a block only when the condition is true:

val age = 20
if (age >= 18) {
    println("You are an adult")
}

Output: You are an adult

3.2 If-Else

Handles both true and false conditions:

val temperature = 30
if (temperature > 35) {
    println("It's very hot")
} else {
    println("Temperature is moderate")
}

Output: Temperature is moderate

3.3 If-Else If Ladder

Check multiple conditions in sequence:

val score = 85

if (score >= 90) {
    println("Grade A")
} else if (score >= 75) {
    println("Grade B")
} else if (score >= 60) {
    println("Grade C")
} else {
    println("Fail")
}

Output: Grade B

3.4 Using If as an Expression

In Kotlin, if can return a value:

val max = if (10 > 5) 10 else 5
println("Max value: $max")

Output: Max value: 10

4. Key Points

5. Interview Questions

Why Use If-Else?

How If-Else Works?

Other Common Questions