else and else if
- Kotlin course
- Beginner
- Lesson 37/116
- 4 min
Learn else and else if chains for alternative cases.
else and else if
When the if condition is false, else runs an alternative block. To list several conditions, else if comes in.
val age = 12
if (age >= 18) {
println("Adult")
} else {
println("Child")
}Here age is below 18, so the else block runs and prints "Child". If the condition is true, else is skipped.
else is optional; it runs only when all previous conditions are false.
else if chains
For three or more cases, an else if chain is used. Conditions are tried top to bottom; the first true one runs its block.
val score = 75
if (score >= 90) {
println("A")
} else if (score >= 80) {
println("B")
} else if (score >= 70) {
println("C")
} else {
println("F")
}score is 75, so the first two conditions are false and the third is true; "C" is printed. The rest are not tried.
Order matters: stricter conditions must come first.
Practice Convert score to a letter grade
Write a fun main(). Assign 75 to val score. Use an if/else if/else chain to print the letter grade: 90+ "A", 80+ "B", 70+ "C", else "F".
Starter code
fun main() {
// Convert score to a letter grade
}Sample solution
fun main() {
val score = 75
if (score >= 90) {
println("A")
} else if (score >= 80) {
println("B")
} else if (score >= 70) {
println("C")
} else {
println("F")
}
}Expected output
C
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the if/else flow
| Term | Meaning |
|---|---|
if condition true |
if block runs |
if condition false |
else block runs |
no else |
Nothing happens |
several conditions |
else if chain |
2 x = -5: which block runs? if (x > 0) { ... } else { ... }
- if block
- if then else
- Skipped
- else block Correct answer
Explanation: -5 > 0 is false, so the else block runs.
3 Complete the else if branch
} ____ (score >= 80) {
} else if (score >= 80) {
Explanation: } else if (score >= 80) { adds the second condition.