JavaRush /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 something else in others.

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

A conditional statement consists of three parts: a 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
else
   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. A block of commands

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

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 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 block of commands 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 the code in the else block is missing, 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 will change 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 helps:

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, it's morning.
  • If it's from 12 to 18, it's afternoon.
  • If it's later, it's evening.
  • The program chooses only ONE option! As soon as a condition matches, the others 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 really resembles forks in tabletop RPGs: go left—one thing, go right—another, go straight—something else!

6. What conditions can you check?

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 sign) is assignment. == (two signs) is comparison. This is one of the most popular mistakes among beginners! If you accidentally write:

if (x = 5) // ERROR!

the compiler will scold you—and it will be absolutely right.

7. Working with strings in conditions

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

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

val password = readln()
if (password == "qwerty")
{
    println("You are logged in!")
}

8. Features and nuances:

Curly braces: needed or not?

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

if (age > 18)
    println("You are older than 18!")

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

Tip: always write braces. This protects you from a lot of mistakes, especially when extending code.

Logic errors: be careful with conditions!

If you write this:

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

then the compiler will read this code like this:

if (age > 18)
{
    println("You are older than 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