Let's think about it this way
This lesson isn't teaching content — it's a set of 4 practice tasks to self-test the concepts you learned in the Basics chapter: val/var, data types, if/when expressions, loops, and null safety. For each task, we recommend trying to write the solution yourself before looking at the answer. The difficulty is easy, aimed at refreshing your syntax memory and getting hands-on practice with the core concepts. All the tasks can be solved within a single function.
Exercises
Task 1: Declare two Int variables a and b, and use a when expression to print a message for the 3 cases a > b, a < b, and a == b. Task 2: Loop through numbers 1 to 20 with a for loop, and for each number print "Fizz" if divisible by 3, "Buzz" if divisible by 5, "FizzBuzz" if divisible by both, and otherwise the number itself (classic FizzBuzz). Task 3: Declare a nullable String? variable and print its length using the safe call operator (?.) — if the value is null, print "no value". Task 4: Using a while loop, calculate the sum of all the even numbers in an Int array/list.
Code Example
fun main() {
// Task 1: compare numbers with when
val a = 7
val b = 12
when {
a > b -> println("a is bigger")
a < b -> println("b is bigger")
else -> println("equal")
}
// Task 2: FizzBuzz 1..20
for (i in 1..20) {
val result = when {
i % 15 == 0 -> "FizzBuzz"
i % 3 == 0 -> "Fizz"
i % 5 == 0 -> "Buzz"
else -> i.toString()
}
println(result)
}
// Task 3: nullable safe call
val name: String? = null
println(name?.length ?: "no value")
// Task 4: sum of even numbers with while loop
val numbers = listOf(3, 8, 12, 5, 20, 7, 6)
var index = 0
var sum = 0
while (index < numbers.size) {
if (numbers[index] % 2 == 0) sum += numbers[index]
index++
}
println("Even sum: $sum")
}You'll see a comparison message, the FizzBuzz sequence from 1 to 20, the text 'no value', and the sum of even numbers in the console.5-Minute Challenge
Rewrite Task 4's while loop using a single forEach lambda instead, and compare how much shorter the code gets — spend about 5 minutes on this.
A Quick Warning
When working through these practice tasks, you'll learn more by running the code yourself in an IDE or the Kotlin Playground and fixing errors on your own, rather than jumping straight to the solution code.