In this tutorial, you shall learn how to use AND logical operator in the condition of If-statement in Kotlin, with examples.
Kotlin If with AND 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 AND 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 | false |
| false | true | false |
| 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 5 and if this number even.
The expression to check if a is greater than 5, is a > 5.
The expression to check if a is even is a%2 == 0.
We shall join these two simple boolean conditions using AND operator && to form a compound boolean condition.
Main.kt
fun main(args: Array<String>) {
val a = 10
if ( (a > 5) && (a%2 == 0) ) {
print("$a is even and greater than 5.")
}
}
Output
10 is even and greater than 5.
Conclusion
In this Kotlin Tutorial, we learned how to use Logical AND Operator in If-statement’s boolean condition, with the help of example programs.
