In this tutorial, you shall learn about the If conditional statement in Kotlin, its syntax, and how to write an If statement in programs with examples.

Kotlin If

Kotlin If-statement conditionally executes a block of statements. If-statement has a condition and a block of statements.

If the condition evaluates to true, then the block of statements in If-statement will execute, else the execution continues with the statement(s), if any, after the If-statement.

Syntax

The syntax of If conditional statement is

</>
Copy
if (condition) {
    //code
}

The condition should be a boolean expression, or must evaluate to a boolean value.

Examples

1. Check if N is even number using If-statement

In the following Kotlin program, we have an integer value in n. We shall check if this integer is even or not, using if statement. If n is the value in which the integer is, then the condition to check if n is even is n%2 == 0.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    val n = 10
    if (n%2 == 0) {
        print("$n is even number.")
    }
}

Output

10 is even number.

2. Check if N is odd number using If-statement

Now, let us check if n is an odd number or not.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    val n = 9
    if (n%2 == 1) {
        print("$n is odd number.")
    }
}

Output

9 is odd number.

Conclusion

In this Kotlin Tutorial, we learned what is If statement in Kotlin, and how to use it to write conditional statements, with the help of example programs.