Bird
0
0

What is the output of this Kotlin code?

medium📝 Predict Output Q4 of 15
Kotlin - Null Safety
What is the output of this Kotlin code?
val user: String? = null
println(user?.length ?: "No length")
A0
BNo length
Cnull
DThrows NullPointerException
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate safe call on null

    The variable user is null, so user?.length returns null safely.
  2. Step 2: Use Elvis operator to provide default

    The Elvis operator ?: returns "No length" because the left side is null.
  3. Final Answer:

    No length -> Option B
  4. Quick Check:

    Safe call null + Elvis operator = default value [OK]
Quick Trick: Safe call returns null, Elvis operator provides default [OK]
Common Mistakes:
MISTAKES
  • Expecting 0 instead of default string
  • Thinking it throws exception
  • Confusing null output with string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes