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 = trueval b = falseval c = a && b // false because both are not true
OR operator returns true if at least one side is true.
Kotlin
val a = trueval b = falseval c = a || b // true because one side is true
NOT operator flips true to false and false to true.
Kotlin
val a = trueval 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 = trueval 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.
Practice
(1/5)
1. What type of value does the Kotlin Boolean type store?
easy
A. Decimal numbers
B. True or false values
C. Text strings
D. Numbers only
Solution
Step 1: Understand the Boolean type
The Boolean type in Kotlin is designed to hold only two possible values: true or false.
Step 2: Identify the correct value type
Since Boolean stores true or false, it cannot store numbers or text strings.
Final Answer:
True or false values -> Option B
Quick Check:
Boolean = true/false [OK]
Hint: Boolean means true or false only [OK]
Common Mistakes:
Thinking Boolean stores numbers
Confusing Boolean with String
Assuming Boolean can hold multiple values
2. Which of the following is the correct syntax for the logical AND operator in Kotlin?
easy
A. &&
B. ||
C. and
D. !
Solution
Step 1: Recall Kotlin logical operators
Kotlin uses && for logical AND, || for OR, and ! for NOT.
Step 2: Match operator to AND
The operator && combines two Boolean expressions and returns true only if both are true.
Final Answer:
&& -> Option A
Quick Check:
AND operator = && [OK]
Hint: AND is double ampersand && in Kotlin [OK]
Common Mistakes:
Using || instead of && for AND
Writing 'and' as a keyword
Confusing NOT (!) with AND
3. What is the output of the following Kotlin code?
val a = true
val b = false
println(a || b && !b)
medium
A. false
B. null
C. true
D. Compilation error
Solution
Step 1: Evaluate NOT operator
!b means !false, which is true.
Step 2: Evaluate AND operator
b && !b means false && true, which is false.
Step 3: Evaluate OR operator
a || (result of AND) means true || false, which is true.
Final Answer:
true -> Option C
Quick Check:
Logical operators follow precedence: !, &&, then || [OK]