In Kotlin, conditional statements are essential for controlling the flow of statements in the program. If Else statement executes a particular statement based on conditions. This tutorial will teach us how to use If-Else Conditional Statements in Kotlin with easy examples.
If-Else Conditional Statement in Kotlin: A Beginner’s Guide with Examples
What is If-Else?
In Kotlin If-Else allows us to execute a code of block when a certain condition is true. If the condition is false then it will execute the Else part of the statements.
Syntax:
1 2 3 4 5 6 7 8 9 10 |
if (condition) { // Code to execute if the condition is true } else { // Code to execute if the condition is false } |
Example 1:
In this example, we will check whether a Number is positive or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { val number = 10 if (number > 0) { println("$number is a positive number.") } else { println("$number is a negative number.") } } // Output 10 is a positive number. |
In the same above-mentioned example, we will pass the value in minus then it will execute the else part.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { val number = -12 if (number > 0) { println("$number is a positive number.") } else { println("$number is a negative number.") } } // Output -12 is a negative number. |
Example 2:
In this example, we will use If-Else with multiple conditions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
fun main() { val number = 8 if (number > 0) { println("$number is positive.") if (number % 2 == 0) { println("$number is even.") } else { println("$number is odd.") } } else if (number < 0) { println("$number is negative.") } else { println("$number is zero.") } } // Output 8 is positive. 8 is even. |
With If-Else we can control the flow of our program and change the direction of our program on a certain condition. Keep practicing the code and you will get used to it. If anything is required from my side please feel free to comment, Happy coding.