Kotlin if-else statement

Learn how to use if-else statements in Kotlin to control program flow with clear, concise syntax

If statements, commonly found in most programming languages, are control flow structures used to direct or alter the execution path of a program based on specific conditions. It’s no different for Kotlin, in Kotlin we use if statements to decide what block of code to execute if certain predefined conditions are met or not.

A key feature of Kotlin’s if statement in is that the if construct is not merely a statement, but an expression, meaning it can return a value. This allows the result of an if-else block to be assigned directly to a variable, leading to more concise and functional style code.

Kotlin provides the when statement, which can be seen as a more powerful and flexible version of the traditional switch statement, and can also be used in place of complex if-else if chains.

Kotlin if statement syntax

The general syntax consists of the if keyword, followed by a condition enclosed in parentheses, and a block of code within curly braces that executes only if the condition is true.

Kotlin

This is the general syntax of the if statement in Kotlin, let’s explore some examples

Example one (1):
Suppose you have a variable that holds the temperature of a room. Write a Kotlin program that prints "It’s warm" only if the temperature is above 25 degrees. If it’s 25 or below.

Solution one(1):

Kotlin

Output:

json

Example two(2):

Suppose we have a bag full of oranges, some green, some yellow, and some orange (in color). We need to filter out the green (unripe) oranges and count the number of yellow and orange-colored ones. Write a Kotlin program to achieve this.

Solution two(2):

Kotlin

Output:

Kotlin

So, this Kotlin program counts ripe oranges (yellow or orange). It starts with a list of orange colors and a counter set to 0. Using a for loop, it checks each orange. The condition orange == "yellow" || orange == "orange" determines if the orange is ripe. If true, the counter increases by 1. After checking all oranges, it prints the total ripe count.

Kotlin else if clause

Sometimes, you may need to check multiple different conditions when making decisions in your code. In such cases, Kotlin provides the else if clause, which lets you test another condition if the initial if condition is false. This allows your program to choose between several possible actions based on varying inputs, states, or conditions.

Kotlin

So, from the code above, notice how if the first condition is not met, the code checks the second condition, and if that is also not met, it checks the third condition. This process of evaluating a chain of multiple conditions is made possible by using the else if clause. The else if clause allows us to check for multiple conditions one after another. Let’s explore some examples of how we can use the else if clause.

Example three(3):

Let’s revisit Example 2 and update the problem: Suppose we have a bag full of oranges, some green, some yellow, and some orange (in color). We need to count the number of green (unripe) oranges, yellow (semi-ripe) oranges, and orange-colored (ripe) oranges, and determine the count of each type.

Solution:

Kotlin

Output:

json

From the example above, we can clearly see how the code checks each type of orange using separate conditions. The first if clause checks for green oranges, the next else if clause checks for yellow oranges, and the third checks for orange-colored oranges. Clearly, the else if clause gives us the flexibility to make more precise decisions in our program.

Let’s observe the else if clause flow diagram below.

We have seen how the if clause allows us to run a block of code based on a specific condition. We have also seen how the else if clause lets us define multiple conditions, logically determining which block of code to execute.

But what happens if the program evaluates all of these conditions and none of them resolve to true? What should our code do then? This is where the else clause comes into play.

Kotlin else clause

The else clause provides a default block of code to run when none of the preceding if or else if conditions are met. It acts as a catch-all ensuring that your program has a specific action to perform in any situation.

Unlike if and else if, the else clause does not have its own condition; it simply executes if all other conditions have failed. Let’s explore example four(4)

Example Four(4)

Suppose we are building a simple automated grading system for a school. The program must evaluate a student's numerical test score and assign a corresponding performance message based on a set of rules.

The rules for grading are as follows:

  • A score of 90 or higher should receive an "Excellent" message.

  • A score from 80 up to 89 should receive a "Good job" message.

  • A score from 70 up to 79 should receive a "You passed" message.

  • Any score below 70 is considered a failing grade and should receive a message encouraging the student to try again.

Write a Kotlin program that takes a single score as input and uses conditional logic to print the correct message to the console.

Solution

Kotlin

Output

json

This structure guarantees that exactly one block of code will be run. As soon as the program finds a condition that is true, it runs that block and skips all the rest. If no conditions are true, the else block is run.

Exercise

Suppose you are developing a simple application that provides a personalized greeting to a user based on the current time of day. The program will use a 24-hour format to represent the current hour (e.g., 9 for 9 AM, 13 for 1 PM, 22 for 10 PM).

The program must follow these rules to generate the correct greeting:

  • If the hour is before 12 (noon), it should print "Good morning!"

  • If the hour is from 12 up to 17 (5 PM), it should print "Good afternoon!"

  • If the hour is from 17 up to 20 (8 PM), it should print "Good evening!"

  • For any other time (i.e., from 8 PM onwards), it should print "Good night!"

  • Your Task:

Write a Kotlin program that takes an integer representing the current hour and uses an if-else if-else structure to print the appropriate greeting to the console.

The if, else if, and else structure in Kotlin provides a clear and efficient method for controlling program flow. It evaluates conditions sequentially and executes the corresponding block, ensuring consistent and logical execution.

Ads