Kotlin if-else Statement Tutorial 🎯

beginner
10 min

Kotlin if-else Statement Tutorial 🎯

Welcome to our deep dive into the if-else statement in Kotlin! This tutorial is designed to help you understand this fundamental control structure, perfect for beginners and intermediates alike. 📝

What is an if-else Statement? 💡

An if-else statement is a programming construct that lets you test conditions and execute different code blocks based on the result. It's a powerful tool for making decisions in your code.

Basic Syntax 📝

Here's the basic syntax for the if-else statement in Kotlin:

kotlin
if (condition) { // Code block executed if condition is true } else { // Code block executed if condition is false }

Example 1: Simple if-else Statement 🎯

Let's see a simple example where we check if a number is even or odd:

kotlin
fun checkNumber(number: Int) { if (number % 2 == 0) { println("The number is even.") } else { println("The number is odd.") } } checkNumber(5) // Output: The number is odd. checkNumber(6) // Output: The number is even.

Advanced if-else Statements 💡

You can also use multiple if-else statements in a chain to test multiple conditions:

kotlin
fun grade(score: Int) { if (score >= 90) { println("A") } else if (score >= 80) { println("B") } else if (score >= 70) { println("C") } else if (score >= 60) { println("D") } else { println("F") } } grade(85) // Output: B grade(70) // Output: C

Nested if-else Statements 💡

Sometimes, you may need to nest one if-else statement inside another:

kotlin
fun checkAge(age: Int) { if (age >= 18) { println("You are an adult.") if (age >= 65) { println("You are a senior citizen.") } } else { println("You are a minor.") } } checkAge(18) // Output: You are an adult. checkAge(66) // Output: You are an adult. You are a senior citizen.

Quiz: If-else Statement Practice 🎯

Quick Quiz
Question 1 of 1

Given the following code, what will be the output when `isTall` is set to `true` and `weight` is set to `70`?