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 obj: Any = 123
val str: String? = obj as? String
println(str)
Anull
BClassCastException
C123
D"123"
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the cast attempt

    Variable obj holds an integer 123, but we try to cast it to String using safe cast as?.
  2. Step 2: Safe cast behavior

    Since obj is not a String, the safe cast returns null instead of throwing an error.
  3. Final Answer:

    null -> Option A
  4. Quick Check:

    Safe cast fails = null output [OK]
Quick Trick: Safe cast returns null if types mismatch [OK]
Common Mistakes:
MISTAKES
  • Expecting ClassCastException instead of null
  • Thinking it converts integer to string automatically
  • Confusing safe cast with forced cast

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes