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?
var text: String? = null
println(text?.length ?: "No length")
A0
Bnull
CNo length
DThrows NullPointerException
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe call and Elvis operator

    text?.length safely accesses length if text is not null; else returns null. The Elvis operator ?: provides "No length" if left side is null.
  2. Step 2: Evaluate given code

    Since text is null, text?.length is null, so the expression prints "No length".
  3. Final Answer:

    No length -> Option C
  4. Quick Check:

    Safe call + Elvis = fallback value [OK]
Quick Trick: Safe call ?. returns null safely; ?: provides default [OK]
Common Mistakes:
MISTAKES
  • Expecting NullPointerException on null safe call
  • Thinking null?.length returns 0
  • Ignoring Elvis operator fallback

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes