Bird
0
0

What is the output of the following Kotlin code?

medium📝 Predict Output Q4 of 15
Kotlin - Control Flow as Expressions
What is the output of the following Kotlin code?
val x = 3
val result = when (x) {
  1 -> "One"
  2 -> "Two"
  3 -> "Three"
  else -> "Unknown"
}
println(result)
ATwo
BThree
COne
DUnknown
Step-by-Step Solution
Solution:
  1. Step 1: Match the value of x in when expression

    The value of x is 3, so the branch with 3 -> "Three" matches.
  2. Step 2: Return the matched branch value

    The when expression returns "Three" which is printed.
  3. Final Answer:

    Three -> Option B
  4. Quick Check:

    when match for 3 = "Three" [OK]
Quick Trick: when returns matched branch value, printed output matches it [OK]
Common Mistakes:
MISTAKES
  • Choosing else branch incorrectly
  • Confusing value 2 with 3
  • Assuming when returns Boolean

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes