If Else in Kotlin | Kotlin If Else Expression – Apkfear

0

In this article, we will learn about If else in Kotlin. If you are a programmer. Then you already know about Expression. If else expression is a very important expression. If Else in Kotlin is used to test multiple conditions in Kotlin.

If Else in Kotlin

Programmers can use only If expression. Without else expression. The usage of expressions depends on the situation. Sometimes we have to test only one condition. In that case, only If expression is required.

Do you know how its works?  If the condition is written in If the block is Right. Then If the statement works successfully. Otherwise Else statements work.

Syntax of if expression

If (Condition) {

//lines of codes

//lines of codes

}

Example

fun main() {

    var num = 5

    if(num > 2){

        print(“yes”)

    }

}

Output

yes

Explanation

In If Condition we used conditional operator. Operators are nothing. It is symbols that tell the compiler which actions performed on variables.

If Else in Kotlin

Syntax of If else Expression

If (Condition) {

//lines of codes

//lines of codes

}

else{

//lines of codes

//lines of codes

}

Example

Kotlin Program division by zero

If Else in Kotlin

Output

Divsion by zero not allowed.

#Kotlin program to check greatest of two number

fun main() {

    var num1 = 5

    var num2 = 8

    if(num1 > num2){

        print(“First number is greatest”)

    }

    else{

        print(“Second number is greatest”)

    }

}

Output

Second number is greatest

Nested If Else in Kotlin

In some cases, we have to test the multiple conditions. In that case, If Else’s statement is not sufficient. Now we have to need the Nested If Else Statements.

Syntax of Nested If else statement

If (Condition) {

//lines of codes

//lines of codes

}

else if(Condition) {

//lines of codes

//lines of codes

}

……….

……….. and so on.

else{

//lines of codes

//lines of codes

}

Example

#Kotlin program to check greatest of three number

fun main() {

    var numer1 = 5

    var numer2 = 8

    var numer3 = 2

    if(numer1 > numer2 && numer1 > numer3){

        print(“First number is greatest”)

    }

    else if(numer2 > numer1 && numer2 > numer3){

        print(“Second number is greatest”)

    }

    else{

        print(“Third number is greatest”)

    }

}

Output

Second number is greatest

If Else in Kotlin is the heart of programming. It is very helpful in making a decision.

Leave A Reply

Your email address will not be published.