0
0
Kotlinprogramming~20 mins

Primary constructor and init blocks in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Primary Constructor and Init Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of init block with primary constructor
What is the output of this Kotlin code?
Kotlin
class Person(val name: String) {
    init {
        println("Hello, $name")
    }
}

fun main() {
    val p = Person("Anna")
}
AHello, name
BCompilation error
CNo output
DHello, Anna
Attempts:
2 left
💡 Hint
The init block runs right after the primary constructor.
Predict Output
intermediate
2:00remaining
Value of property after init block
What is the value of 'age' after creating the object?
Kotlin
class User(val name: String, val birthYear: Int) {
    val age: Int
    init {
        age = 2024 - birthYear
    }
}

fun main() {
    val u = User("Tom", 1990)
    println(u.age)
}
ACompilation error
B0
C34
D1990
Attempts:
2 left
💡 Hint
Age is calculated in the init block using birthYear.
Predict Output
advanced
2:00remaining
Multiple init blocks execution order
What is the output of this Kotlin code?
Kotlin
class Box(val width: Int) {
    init {
        println("First init: width = $width")
    }
    init {
        println("Second init: width * 2 = ${width * 2}")
    }
}

fun main() {
    val b = Box(5)
}
A
First init: width = 5
Second init: width * 2 = 10
B
Second init: width * 2 = 10
First init: width = 5
CFirst init: width = 5
DCompilation error
Attempts:
2 left
💡 Hint
Init blocks run in the order they appear in the class.
Predict Output
advanced
2:00remaining
Property initialization with primary constructor and init
What is the output of this Kotlin program?
Kotlin
class Rectangle(val height: Int, val width: Int) {
    val area: Int
    init {
        area = height * width
    }
}

fun main() {
    val r = Rectangle(3, 4)
    println(r.area)
}
A7
B12
C0
DCompilation error
Attempts:
2 left
💡 Hint
Area is calculated in the init block from height and width.
Predict Output
expert
2:00remaining
Effect of property shadowing in init block
What is the output of this Kotlin code?
Kotlin
class Sample(x: Int) {
    val x: Int = x + 1
    init {
        println(this.x)
    }
}

fun main() {
    val s = Sample(5)
}
A6
B5
CCompilation error
DRuntime error
Attempts:
2 left
💡 Hint
Class property shadows constructor parameter; init uses property.