0
0
Kotlinprogramming~5 mins

Boolean type and logical operators in Kotlin

Choose your learning style9 modes available
Introduction

Boolean type helps us store true or false values. Logical operators let us combine or change these true/false values to make decisions.

Checking if a light switch is on or off
Deciding if a user can log in based on username and password
Determining if a number is both positive and even
Checking if a door is locked or if an alarm is active
Combining multiple conditions to control game actions
Syntax
Kotlin
val isTrue: Boolean = true
val isFalse: Boolean = false

// Logical operators
val andResult = true && false  // AND
val orResult = true || false   // OR
val notResult = !true          // NOT

Boolean values are either true or false.

Logical operators combine Boolean values: && means both must be true, || means at least one is true, ! flips true to false and vice versa.

Examples
AND operator returns true only if both sides are true.
Kotlin
val a = true
val b = false
val c = a && b  // false because both are not true
OR operator returns true if at least one side is true.
Kotlin
val a = true
val b = false
val c = a || b  // true because one side is true
NOT operator flips true to false and false to true.
Kotlin
val a = true
val b = !a  // false because NOT flips the value
Sample Program

This program uses Boolean values and logical operators to decide if we should take an umbrella and if we can go outside.

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

    // Should we take an umbrella?
    val takeUmbrella = isRaining && haveUmbrella
    println("Take umbrella: $takeUmbrella")

    // Should we go outside?
    val canGoOutside = !isRaining || haveUmbrella
    println("Can go outside: $canGoOutside")
}
OutputSuccess
Important Notes

Remember, && needs both sides true to return true.

|| returns true if any side is true.

! flips the Boolean value.

Summary

Boolean type stores true or false.

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

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