Logical operators
- Kotlin course
- Beginner
- Lesson 27/116
- 4 min
Learn boolean logic with &&, || and !.
Logical operators
Logical operators combine Boolean values: && (and), || (or), ! (not). && yields true when both sides are true. || yields true when at least one side is true. ! flips true to false.
val a = true
val b = false
println(a && b) // false
println(a || b) // true
println(!a) // falsePractice Try logical
Write a fun main(). Declare val age = 20. Check the age range with println(age >= 18 && age <= 65).
Sample solution
fun main() {
val age = 20
println(age >= 18 && age <= 65)
}Expected output
true
Short-circuit evaluation
&& and || are short-circuit operators. In a && b, if a is false, b is not evaluated; the result is already false. In a || b, if a is true, b is not evaluated.
This behavior is especially useful for null checks: x != null && x.length > 0 is safe; if x is null, the second part is not run.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does `true && false` return?
- true
- null
- false Correct answer
- It throws an error
Explanation: && yields true only when both sides are true.
2 Logical operators: match the terms
| Term | Meaning |
|---|---|
&& |
And |
|| |
Or |
! |
Not |
== |
Equal |
3 Logical operators: fill in the missing part
val result = (3 > 2) ____ (5 > 10)
println(result) // true
val result = (3 > 2) || (5 > 10)
println(result) // true
Explanation: With || the result is true if at least one condition holds.