CodeGym /Courses /Kotlin SELF /Conditional statement: if else

Conditional statement: if else

Kotlin SELF
Level 3, Lesson 1
Available

1. The if else statement

Programs would be of little use if they did the same thing regardless of how external circumstances change. A program needs to be able to adapt to different situations and do one thing in some cases and another thing in others.

In Kotlin, this is implemented using a conditional statement — a special keyword that allows executing different blocks of commands depending on whether the condition is true.

A conditional statement consists of three parts: the condition, command 1, and command 2. If the condition is true, command 1 is executed; otherwise, command 2 is executed. The commands are never executed at the same time. The general form of this statement is:

if (condition)
    command 1
else
    command 2
Conditional statement if-else

if translates as “if”, and else as “otherwise”. In plain language, it can be written like this:

If condition is true, then
   execute command1
otherwise
   execute command2
Conditional statement if-else in plain language

Examples:

// The following text will be printed: You are still a child

val age = 17
if (age < 18)
   println("You are still a child")
else
   println("You are already an adult")
// The following text will be printed: Warm

val temperature = 5
if (temperature < 0)
   println("It's freezing outside")
else
   println("Warm")
// The following text will be printed: You can apply for a driver's license

val age = 18
if (age == 18)
   println("You can apply for a driver's license")
else
   println("You can save up for a car")

2. Command block

If when a condition is met (or not met) you want your program to execute multiple commands, you can combine them into a command block.

To combine commands into a block, you need to “wrap” them in curly braces. Here is what it looks like in the general case:

{
   command1
   command2
   command3
}

There can be as many commands in a block as you want. Even zero.

Examples of combining the if-else statement and a command block:

// The following text will be printed: You are still a child. Don't argue with adults

val age = 17
if (age < 18)
{
   println("You are still a child")
   println("Don't argue with adults")
}
else
{
   println("You are already an adult")
   println("Kids these days")
}
// The following text will be printed: Warm

val temperature = 5
if (temperature < 0)
{
   println("It's freezing outside")
   println("Put on a hat")
}
else
   println("Warm")
// An empty command block will be executed. Nothing will be printed.

val age = 21
if (age == 18)
   println("You can get a driver's license")
else
{
}

3. Shortened syntax of the if statement

If there is no code in the else block, it can be omitted. Then the if statement will look like this:

if (condition)
{
    command1
}
Conditional statement if

Example:

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

How does it work?

  • If the condition is true, the code block is executed. If it is false, nothing happens — the program continues.
  • The else block exists in the program, but it is empty (there are no commands between the curly braces). You can simply remove it: nothing changes in the program.

4. Combining conditions: else if

Sometimes you need to check not just “yes/no”, but choose from several options.
This is where the else if chain comes in:

if (condition1)
{
    // Executed if condition1 is true
}
else if (condition2)
{
    // Executed if condition2 is true and condition1 is false
}
else
{
    // Executed if none of the conditions above matched
}

Example:

val hour = 13
if (hour < 12)
{
    println("Good morning!")
}
else if (hour < 18)
{
    println("Good afternoon!")
}
else
{
    println("Good evening!")
}

What is happening here?

  • If the time is before 12 — morning.
  • If it is from 12 to 18 — afternoon.
  • If it is later — evening.
  • The program chooses only ONE option! As soon as a condition matches, the rest are not even checked.

5. Schematic illustration: branching flowchart

Here is what it looks like as a flowchart:

Branching flowchart

And if there are multiple conditions:

Flowchart: multiple conditions

This strongly resembles forks in tabletop RPGs: go left — one thing, go right — another, go straight — something else!

6. What conditions can be checked?

Inside the parentheses after if there must be a LOGICAL expression — the result of which is “true” true or “false” false.

Main comparison operators:

Operator Meaning Example
==
Equal
x == 5
!=
Not equal
x != 10
>
Greater than
x > 0
<
Less than
age < 18
>=
Greater than or equal
score >= 100
<=
Less than or equal
count <= 50

Examples of conditions:

if (number == 10)
if (age != 18)
if (temperature > 36)
if (balance <= 0)

Note: = (one symbol) is assignment. == (two symbols) is comparison. This is one of the most common mistakes among beginners! If you accidentally write:

if (x = 5) // ERROR!

— the compiler will scold you, and it will be absolutely right to do so.

7. Working with strings in conditions

Comparison using == in Kotlin compares values (contents). Therefore, strings can be compared using == (unlike Java). At the same time, you should be more careful with floating-point numbers (Double/Float): due to calculation inaccuracies, comparison using == may produce unexpected results.

We will talk more about the subtleties of string comparison later. And you can learn how to properly compare strings from the example below:

val password = readln()
if (password == "qwerty")
{
    println("Logged in!")
}

8. Features and nuances:

Curly braces: required or not?

If after if or else there is only one command, curly braces can be omitted:

if (age > 18)
    println("You are over 18!")

// But it is safer to ALWAYS write them:
if (age > 18)
{
    println("You are over 18!")
}

Tip: always write braces. This will protect you from a bunch of mistakes, especially when expanding code.

Logical errors: be careful with conditions!

If you write it like this:

if (age > 18)
    println("You are over 18!")
    println("Welcome!")

Then the compiler will read this code like this:

if (age > 18)
{
    println("You are over 18!")
}

println("Welcome!")

The second line will always be executed — braces are needed so that both lines are inside the “branch”.

1
Task
Kotlin SELF, level 3, lesson 1
Locked
Heat sensor
Heat sensor
1
Task
Kotlin SELF, level 3, lesson 1
Locked
Code comparison
Code comparison
1
Task
Kotlin SELF, level 3, lesson 1
Locked
Nickname validation
Nickname validation
1
Task
Kotlin SELF, level 3, lesson 1
Locked
Price comparison
Price comparison
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION