Bird
0
0

What will be printed by this Kotlin code?

medium📝 Predict Output Q5 of 15
Kotlin - Operators and Expressions

What will be printed by this Kotlin code?

val x: Int? = null
val y: Int? = 10
val z = x ?: y ?: 5
println(z)
Anull
B5
C10
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate first Elvis operator

    x is null, so x ?: y returns y, which is 10.
  2. Step 2: Evaluate second Elvis operator

    Since y is not null, y ?: 5 returns 10.
  3. Final Answer:

    10 -> Option C
  4. Quick Check:

    Elvis operator returns first non-null value in chain [OK]
Quick Trick: Elvis operator picks first non-null left to right [OK]
Common Mistakes:
MISTAKES
  • Expecting default 5 to print
  • Confusing null with zero
  • Ignoring chaining order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes