The if statement
- Kotlin course
- Beginner
- Lesson 36/116
- 4 min
Learn how to check a condition with if.
The if statement
The if statement runs a block when a condition is true. The condition goes in parentheses; the block is wrapped in curly braces.
val age = 18
if (age >= 18) {
println("Adult")
}The condition is a Boolean expression: true or false. If true, the block runs; if false, it is skipped. Comparison operators (>, <, ==, >=, <=) were covered earlier.
For single-line blocks the braces are optional, but recommended for readability.
Comparison and logical operators
Conditions use comparison operators. These were covered earlier but let's quickly recap.
5 > 3 // true
5 < 3 // false
5 == 5 // true
5 != 3 // true
5 >= 5 // true
5 <= 4 // false== checks value equality, != checks inequality. For Strings, == compares content too (unlike Java).
Logical operators && (and), || (or), ! (not) combine conditions: age >= 18 && age < 65.
Practice Check the age
Write a fun main(). Assign 20 to val age. Use if (age >= 18) to print println("Adult").
Starter code
fun main() {
// Check the age
}Sample solution
fun main() {
val age = 20
if (age >= 18) {
println("Adult")
}
}Expected output
Adult
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does if (age >= 18) run?
- When age is below 18
- When age is 18 or above Correct answer
- Always
- Never
Explanation: >= 18 covers 18 and above.
2 Complete the comparison operator
val adult = age ____ 18
val adult = age >= 18
Explanation: age >= 18 treats 18 and above as adult.
3 Match the conditions
| Term | Meaning |
|---|---|
age >= 18 |
18 or above |
age < 18 |
Below 18 |
age == 18 |
Exactly 18 |
age != 18 |
Not 18 |