0
0
Kotlinprogramming~5 mins

Logical operators (&&, ||, !) in Kotlin

Choose your learning style9 modes available
Introduction

Logical operators help you make decisions by combining or changing true/false values.

Checking if two conditions are both true before doing something.
Doing something if at least one condition is true.
Reversing a true or false value to check the opposite.
Filtering data based on multiple rules.
Controlling program flow with complex conditions.
Syntax
Kotlin
condition1 && condition2  // AND: true if both true
condition1 || condition2  // OR: true if at least one true
!condition               // NOT: reverses true/false

&& means both conditions must be true.

|| means one or both conditions can be true.

Examples
AND example: result is false because b is false.
Kotlin
val a = true
val b = false
val result = a && b
OR example: result is true because a is true.
Kotlin
val a = true
val b = false
val result = a || b
NOT example: result is false because it reverses a.
Kotlin
val a = true
val result = !a
Sample Program

This program decides if you should take an umbrella based on weather and what you have.

Kotlin
fun main() {
    val isSunny = true
    val haveUmbrella = false

    if (isSunny && !haveUmbrella) {
        println("Go outside without umbrella.")
    } else if (!isSunny || haveUmbrella) {
        println("Better take an umbrella.")
    }
}
OutputSuccess
Important Notes

Use parentheses to group conditions for clarity, like (a && b) || c.

Logical operators work with Boolean values: true or false.

NOT (!) flips true to false and false to true.

Summary

Logical operators combine or change true/false values.

Use && for AND, || for OR, and ! for NOT.

They help control decisions in your program.