0
0
Kotlinprogramming~20 mins

When without argument in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
When Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of when without argument with conditions
What is the output of this Kotlin code using when without an argument?
Kotlin
fun main() {
    val x = 15
    val result = when {
        x % 3 == 0 -> "Divisible by 3"
        x % 5 == 0 -> "Divisible by 5"
        else -> "Not divisible by 3 or 5"
    }
    println(result)
}
ACompilation error
BDivisible by 3
CNot divisible by 3 or 5
DDivisible by 5
Attempts:
2 left
💡 Hint
Check which condition matches first in the when block.
Predict Output
intermediate
2:00remaining
When without argument with Boolean expressions
What will this Kotlin program print?
Kotlin
fun main() {
    val a = 10
    val b = 20
    val output = when {
        a > b -> "a is greater"
        a == b -> "a equals b"
        else -> "a is smaller"
    }
    println(output)
}
Aa is smaller
Ba equals b
Ca is greater
DRuntime exception
Attempts:
2 left
💡 Hint
Compare the values of a and b carefully.
🔧 Debug
advanced
2:00remaining
Identify the error in when without argument
What error does this Kotlin code produce?
Kotlin
fun main() {
    val num = 5
    val result = when {
        num > 0 -> "Positive"
        num < 0 -> "Negative"
    }
    println(result)
}
APrints "Negative"
BRuntime exception: NullPointerException
CPrints "Positive"
DCompilation error: 'when' must be exhaustive
Attempts:
2 left
💡 Hint
Check if all possible cases are covered in the when expression.
🧠 Conceptual
advanced
1:30remaining
Behavior of when without argument with multiple true conditions
In Kotlin, when using when without an argument, what happens if multiple conditions are true?
AOnly the first true condition's branch executes
BAll matching branches execute sequentially
CThe last true condition's branch executes
DCompilation error due to ambiguity
Attempts:
2 left
💡 Hint
Think about how when expressions work as a control flow.
🚀 Application
expert
2:30remaining
Using when without argument to classify numbers
What is the output of this Kotlin program?
Kotlin
fun main() {
    val n = -7
    val classification = when {
        n > 0 && n % 2 == 0 -> "Positive even"
        n > 0 && n % 2 != 0 -> "Positive odd"
        n < 0 && n % 2 == 0 -> "Negative even"
        n < 0 && n % 2 != 0 -> "Negative odd"
        else -> "Zero"
    }
    println(classification)
}
ANegative even
BPositive even
CNegative odd
DZero
Attempts:
2 left
💡 Hint
Check the sign and parity of n carefully.