In this tutorial, you shall learn how to use OR logical operator in the condition of If-statement in Kotlin, with examples.
Kotlin If with OR Operator
The condition in the If-statement must be a boolean expression or anything that can evaluate to a Boolean value. And this boolean expression can be a compound condition that contains multiple conditions joined by logical operators.
The following is a simple scenario where two simple conditions are joined with Logical OR Operator to form a compound boolean condition.
if (condition1 || condition2) {
//code
}
The truth table for the result of this compound condition or expression is
condition1 | condition2 | condition1 || condition2 |
---|---|---|
true | true | true |
true | false | true |
false | true | true |
false | false | false |
Example
In the following Kotlin program, we have an integer value in a
. We shall check if this integer is greater than 100 or if this number even.
The expression to check if a
is greater than 100, is a > 100
.
The expression to check if a
is even is a%2 == 0
.
We shall join these two simple boolean conditions using OR operator ||
to form a compound boolean condition.
Main.kt
fun main(args: Array<String>) {
val a = 10
if ( (a > 100) || (a%2 == 0) ) {
print("$a is greater than 100 or even number.")
}
}
Output
10 is greater than 100 or even number.
Conclusion
In this Kotlin Tutorial, we learned how to use Logical OR Operator in If-statement’s boolean condition, with the help of example programs.