Bird
0
0

You want to store a user's middle name which might be missing. How should you declare this variable in Kotlin to handle null safely?

hard📝 Application Q8 of 15
Kotlin - Null Safety
You want to store a user's middle name which might be missing. How should you declare this variable in Kotlin to handle null safely?
Avar middleName: String = ""
Bvar middleName: String = null
Cvar middleName: String? = null
Dvar middleName: String? = ""
Step-by-Step Solution
Solution:
  1. Step 1: Understand nullable type usage

    Since middle name can be missing, use nullable type String?.
  2. Step 2: Initialize nullable variable with null

    Assigning null to String? is allowed and safe.
  3. Final Answer:

    var middleName: String? = null -> Option C
  4. Quick Check:

    Nullable String initialized to null = Correct [OK]
Quick Trick: Use ? for variables that can be null [OK]
Common Mistakes:
MISTAKES
  • Assigning null to non-nullable String
  • Using empty string instead of null

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes