Menu
Coddy logo textTech

If Statement

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

You've learned how to create Boolean expressions using comparison and logical operators. Now it's time to use those expressions to control what your program actually does. The if statement lets you execute code only when a condition is true.

The basic structure places a condition inside parentheses, followed by curly braces containing the code to run:

fun main() {
    val temperature = 35
    
    if (temperature > 30) {
        println("It's hot outside!")
    }
}

When Kotlin reaches the if statement, it evaluates the condition. If temperature > 30 is true, the code inside the braces executes. If it's false, Kotlin skips that block entirely and continues with the rest of the program.

You can include multiple statements inside the braces, and you can use any Boolean expression as the condition, including those with logical operators:

fun main() {
    val age = 25
    val hasTicket = true
    
    if (age >= 18 && hasTicket) {
        println("Welcome to the concert!")
        println("Enjoy the show!")
    }
}

Both conditions must be true for the messages to print. This is how programs make decisions: executing different code paths based on the current state of your data.

challenge icon

Challenge

Easy

Write a function checkSpeed that takes speed and returns a warning message if the speed exceeds the limit.

Use an if statement to check if the speed is greater than 60. If it is, return "Warning: Too fast!". Otherwise, return "Speed OK".

Parameters:

  • speed (Int): The current speed

Returns: "Warning: Too fast!" if speed is greater than 60, "Speed OK" otherwise (String)

Try it yourself

fun checkSpeed(speed: Int): String {
    // Write code here
}
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