Logical Operators in Kotlin
On this page (9sections)
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
How It Works
This Kotlin program demonstrates Logical Operators. It first prepares the data it needs, then uses conditional logic to decide the result, and finally prints the output shown in the Sample Output above.
- Declare the variables that hold the program’s data.
- Use conditional statements to handle the different cases.
- Print the final result to the console so you can compare it with the sample output.
Try changing the input values and re-running the program to see how the output changes — this is the fastest way to understand how the logic behaves.