Bird
Raised Fist0
Kotlinprogramming~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of the init block in a Kotlin class with a primary constructor?
easy
A. To declare secondary constructors
B. To run additional code right after the primary constructor initializes properties
C. To define class-level constants
D. To override functions from a superclass

Solution

  1. Step 1: Understand the role of primary constructor

    The primary constructor initializes the properties of the class when an object is created.
  2. Step 2: Identify the purpose of the init block

    The init block runs immediately after the primary constructor to execute extra setup code or validations.
  3. Final Answer:

    To run additional code right after the primary constructor initializes properties -> Option B
  4. Quick Check:

    Init block = extra setup after constructor [OK]
Hint: Init blocks run right after primary constructor [OK]
Common Mistakes:
  • Confusing init block with secondary constructor
  • Thinking init block declares constants
  • Assuming init block overrides superclass methods
2. Which of the following is the correct syntax to declare a primary constructor with two parameters name and age in Kotlin?
easy
A. class Person(name: String, age: Int) { }
B. class Person { constructor(name: String, age: Int) }
C. class Person(name String, age Int) { }
D. class Person(name: String; age: Int) { }

Solution

  1. Step 1: Recall Kotlin primary constructor syntax

    Primary constructor parameters are declared in parentheses after the class name, separated by commas, with types after colons.
  2. Step 2: Check each option

    class Person(name: String, age: Int) { } uses correct syntax: parentheses, commas, colons for types. Options A, B, and D have syntax errors.
  3. Final Answer:

    class Person(name: String, age: Int) { } -> Option A
  4. Quick Check:

    Primary constructor = class Name(params) [OK]
Hint: Primary constructor parameters go inside parentheses after class name [OK]
Common Mistakes:
  • Using semicolons instead of commas
  • Omitting colons before types
  • Confusing primary with secondary constructor syntax
3. What will be the output of this Kotlin code?
class User(val name: String) {
    init {
        println("Welcome, $name!")
    }
}

fun main() {
    val user = User("Anna")
}
medium
A. Compilation error
B. Welcome, name!
C. No output
D. Welcome, Anna!

Solution

  1. Step 1: Understand object creation and init block

    When creating User("Anna"), the primary constructor sets name to "Anna" and then the init block runs.
  2. Step 2: Analyze the init block output

    The init block prints "Welcome, $name!" where $name is replaced by "Anna".
  3. Final Answer:

    Welcome, Anna! -> Option D
  4. Quick Check:

    Init block prints welcome message with name [OK]
Hint: Init block runs on object creation, prints with property values [OK]
Common Mistakes:
  • Expecting no output because println is inside class
  • Confusing variable interpolation syntax
  • Thinking init block runs only on demand
4. Identify the error in this Kotlin class:
class Product(val id: Int) {
    init {
        println("Product ID: $productId")
    }
}
medium
A. Init block cannot use println
B. Primary constructor must be empty
C. Variable productId is not declared
D. Class must have a secondary constructor

Solution

  1. Step 1: Check variable usage in init block

    The init block tries to print productId, but the class has only id declared.
  2. Step 2: Confirm variable declaration

    Since productId is not declared anywhere, this causes a compilation error.
  3. Final Answer:

    Variable productId is not declared -> Option C
  4. Quick Check:

    Use declared property names in init block [OK]
Hint: Use exact property names inside init blocks [OK]
Common Mistakes:
  • Assuming init block can't use println
  • Thinking primary constructor must be empty
  • Believing secondary constructor is mandatory
5. You want to create a Kotlin class Employee with a primary constructor that takes name and salary. You also want to print a welcome message and calculate a 10% bonus right after object creation. Which is the best way to do this?
hard
A. Use primary constructor for parameters and an init block to print message and calculate bonus
B. Use only secondary constructors for all initialization
C. Put all code inside the primary constructor parentheses
D. Use companion object to run code after object creation

Solution

  1. Step 1: Understand primary constructor role

    Primary constructor is for receiving parameters and initializing properties simply.
  2. Step 2: Use init block for extra setup

    Init block runs after constructor to print messages and calculate bonus, keeping code organized.
  3. Step 3: Evaluate other options

    Secondary constructors are unnecessary here; code can't go inside constructor parentheses; companion object is unrelated.
  4. Final Answer:

    Use primary constructor for parameters and an init block to print message and calculate bonus -> Option A
  5. Quick Check:

    Primary constructor + init block = clean setup [OK]
Hint: Use init block for extra setup after primary constructor [OK]
Common Mistakes:
  • Trying to put logic inside constructor parentheses
  • Using secondary constructors unnecessarily
  • Misusing companion object for instance initialization
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard