Kotlin Logical Operators

Introduction

Logical operators in Kotlin are used to combine multiple Boolean expressions or to invert a Boolean value. These operators are essential for making decisions in your code based on multiple conditions. This chapter will cover the different types of logical operators available in Kotlin, along with examples and their syntax.

Types of Logical Operators

1. && (Logical AND)

The logical AND operator returns true if both operands are true. Otherwise, it returns false.

Syntax:

val result = operand1 && operand2

Example:

fun main() {
    val a = true
    val b = false

    val result = a && b
    println("a && b: $result")  // Output: a && b: false
}

2. || (Logical OR)

The logical OR operator returns true if at least one of the operands is true. If both operands are false, it returns false.

Syntax:

val result = operand1 || operand2

Example:

fun main() {
    val a = true
    val b = false

    val result = a || b
    println("a || b: $result")  // Output: a || b: true
}

3. ! (Logical NOT)

The logical NOT operator inverts the value of a Boolean expression. If the expression is true, it returns false, and if it is false, it returns true.

Syntax:

val result = !operand

Example:

fun main() {
    val a = true
    val b = false

    val notA = !a
    val notB = !b

    println("!a: $notA")  // Output: !a: false
    println("!b: $notB")  // Output: !b: true
}

Example Program with Logical Operators

Here is an example program that demonstrates the use of various logical operators in Kotlin:

fun main() {
    val x = 10
    val y = 20
    val z = 10

    // Logical AND
    val andResult = (x < y) && (x == z)
    println("(x < y) && (x == z): $andResult")  // Output: (x < y) && (x == z): true

    // Logical OR
    val orResult = (x > y) || (x == z)
    println("(x > y) || (x == z): $orResult")  // Output: (x > y) || (x == z): true

    // Logical NOT
    val notResult = !(x < y)
    println("!(x < y): $notResult")  // Output: !(x < y): false
}

Conclusion

In this chapter, you learned about the various logical operators available in Kotlin, including logical AND (&&), logical OR (||), and logical NOT (!). Understanding these operators is crucial for making decisions in your Kotlin programs based on multiple conditions.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top