Bird
0
0

What will be the output of this Kotlin code?

medium📝 Predict Output Q13 of 15
Kotlin - Null Safety
What will be the output of this Kotlin code?
val name: String? = null
val displayName = name ?: "Guest"
println(displayName)
Anull
BGuest
Cname
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Check the value of name

    The variable name is explicitly set to null.
  2. Step 2: Apply the Elvis operator

    Since name is null, displayName gets the default value "Guest".
  3. Final Answer:

    Guest -> Option B
  4. Quick Check:

    null ?: "Guest" = "Guest" [OK]
Quick Trick: If left is null, Elvis returns right side [OK]
Common Mistakes:
MISTAKES
  • Assuming it prints null
  • Thinking it prints variable name
  • Expecting a compile error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes