In this tutorial, you shall learn about AND logical operator in Kotlin, its syntax, truth table, and how to use AND logical operator in programs, with examples.
Kotlin AND
Kotlin logical AND Operator takes two boolean values as operands and returns the output of Logical AND gate operation with the operands as inputs.
&&
symbol is used for logical AND Operator.
Syntax
The syntax for logical AND Operator with the two operands is
operand1 && operand2
The operand must be a boolean value, boolean expression, or values that translate to boolean values.
Truth Table
The following is the truth table for Logical AND Gate operation.
operand1 | operand2 | operand1 && operand2 |
---|---|---|
true | true | true |
true | false | false |
false | true | false |
false | false | false |
AND Operator returns true if given two values are true, else it returns false.
For example, if there are two conditions, and if we need to check if both these conditions are true, then we can use logical AND Operator.
Examples
1. Check if n is positive and even number
In the following example, we take an integer value in n
, and check if n
is positive and even number.
Here, there are two conditions. The first condition is to check if the number is positive. The second condition is to check if the number is an even number.
Since we have to check if the number is both positive and even number, we must use logical AND operator.
Main.kt
fun main() {
var n = 10
if (n > 0 && n % 2 == 0) {
println("$n is positive and even.")
}
}
Output
10 is positive and even.
Conclusion
In this Kotlin Tutorial, we learned how to use logical AND Operator to check if two conditions are both satisfied.