Menu
Coddy logo textTech

If - Else

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 30 of 93.

A basic if statement only runs code when the condition is true. But what if you want to do something different when the condition is false? That's where else comes in.

The else block provides an alternative path: code that runs only when the if condition evaluates to false:

fun main() {
    val age = 15
    
    if (age >= 18) {
        println("You can vote!")
    } else {
        println("You're too young to vote.")
    }
}

In this example, since age is 15, the condition age >= 18 is false, so Kotlin skips the first block and executes the else block instead, printing "You're too young to vote."

You can also chain multiple conditions using else if to check several possibilities in sequence:

fun main() {
    val score = 75
    
    if (score >= 90) {
        println("Grade: A")
    } else if (score >= 80) {
        println("Grade: B")
    } else if (score >= 70) {
        println("Grade: C")
    } else {
        println("Grade: F")
    }
}

Kotlin evaluates each condition from top to bottom and executes only the first block whose condition is true. Once a match is found, the remaining conditions are skipped entirely.

challenge icon

Challenge

Easy

You are provided with the following variable:

val temperature = -5

Use if, else if, and else to print a message based on the temperature value:

  • If the temperature is greater than 30, print Hot
  • If the temperature is greater than 20, print Warm
  • If the temperature is greater than 10, print Cool
  • If the temperature is greater than 0, print Cold
  • Otherwise, print Freezing

Try it yourself

fun main() {
    val temperature = -5
    
    // TODO: Write your code below
    // Use if, else if, and else to print the appropriate message based on temperature
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground