Kotlin If with AND Operator
If statement boolean expression can contain multiple conditions joined by logical operators. In this tutorial, we will learn how to use Logical AND Operator (&&) in the boolean condition/expression of Kotlin If-statement.
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.