Welcome to The Coding College! The best way to master Kotlin is through practice. This post provides a variety of Kotlin exercises, ranging from beginner to advanced levels, to help you strengthen your understanding of key concepts. Each exercise comes with a description and sample output to guide you.
1. Beginner-Level Exercises
Exercise 1: Hello World
Write a program to print “Hello, World!” to the console.
Code Example:
fun main() {
println("Hello, World!")
}
Exercise 2: Variables and Arithmetic
Create a program that declares two variables, performs addition, and prints the result.
Task:
- Declare two variables,
a
andb
. - Add them and display the sum.
Code Example:
fun main() {
val a = 10
val b = 20
println("The sum is: ${a + b}")
}
2. Intermediate-Level Exercises
Exercise 1: Age Checker
Write a program to check if a person is eligible to vote (18 years or older).
Code Example:
fun main() {
val age = 20
if (age >= 18) {
println("Eligible to vote.")
} else {
println("Not eligible to vote.")
}
}
Exercise 2: Multiplication Table
Generate and print the multiplication table for a number provided by the user.
Task:
- Use a
for
loop to print the table.
Code Example:
fun main() {
val number = 5
for (i in 1..10) {
println("$number x $i = ${number * i}")
}
}
3. Advanced-Level Exercises
Exercise 1: Class and Objects
Create a class Student
with properties name
and age
. Write a function to display student details.
Code Example:
class Student(val name: String, val age: Int) {
fun displayDetails() {
println("Name: $name, Age: $age")
}
}
fun main() {
val student = Student("Naman", 24)
student.displayDetails()
}
Exercise 2: File Handling
Write a program to create and write content into a file, then read and display the content.
Code Example:
import java.io.File
fun main() {
val fileName = "example.txt"
File(fileName).writeText("Learning Kotlin is fun!")
println(File(fileName).readText())
}
Why Practice Kotlin with The Coding College?
We provide clear, actionable exercises to help you practice coding in real-world scenarios. By working through these exercises, you’ll gain hands-on experience and a deeper understanding of Kotlin’s features.
Conclusion
Practice makes perfect! These exercises are designed to cover a wide range of topics and difficulty levels. Start with the beginner exercises and work your way up to advanced challenges.