Bird
0
0

What is the output of the following Kotlin code?

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

What is the output of the following Kotlin code?

val a: String? = null
val b: String? = "Hello"
val c: String? = null

val result = a ?: b ?: c ?: "Default"
println(result)
AHello
Bnull
CDefault
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate the chained Elvis operators

    Variable a is null, so Elvis operator moves to b. b is "Hello", which is not null.
  2. Step 2: Determine the final value

    Since b is not null, result is assigned "Hello" and the rest is ignored.
  3. Final Answer:

    Hello -> Option A
  4. Quick Check:

    Chained Elvis picks first non-null: Hello [OK]
Quick Trick: Chained Elvis returns first non-null value [OK]
Common Mistakes:
MISTAKES
  • Assuming it returns null if first is null
  • Ignoring chaining and picking last value
  • Thinking it causes a compile error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes