Logical Operators in Kotlin

Definition

These operators are used mainly to check conditions. There are 3 Logical Operations in Kotlin. They are 

  • Logical OR (||)
  • Logical AND (&&)
  • Logical NOT (!)

Syntax

1. Logical OR Operator

In a situation where a same operation is to be performed for the satisfaction of condition1 or condition2, this operator is used. It is represented by '||'

if(condition1 || condition2){
	//Block of Code
}

For example,

if(value.contains("#") || value.contains("*")){
	//Block of Code
}

2. Logical AND Operator

In a situation where the same operation is to be performed for satisfaction all conditions compulsorily, this operator is used. It is reperesented by '&&'

if(condition1 && condition2){
	//Block of Code
}

For example,

if(value.contains("#") && value.contains("*")){
	//Block of Code
}

3. Logical NOT Operator

This operator performs inversion operation of boolean values.

var variable_one = !variable_two

For example,

var value1 = !value2

Logical Operator Example Program in Kotlin

//Logical Operator Example Program in Kotlin
//Operator Kotlin Programs, Basic Kotlin Program
fun main(args: Array<String>) {
    var num1 = 100;
    var check = true

    //Or Operation
    if(num1>1000 || num1 <500){
        println("$num1 satisfies any one of the conditions")
        num1 = 2000
    }

    //And Operation
    if(num1>1000 && num1 <5000){
        println("$num1 satisfies both the conditions")
    }

    //Not Operation
    if(check){
        check = !check
        println("Value of check after Inversion is : $check")
    }

}

Sample Output

100 satisfies any one of the conditions
2000 satisfies both the conditions
Value of check after Inversion is : false