Bird
0
0

You want to safely convert a Java platform type String to uppercase in Kotlin, but the Java method may return null. Which Kotlin code is best?

hard📝 Application Q8 of 15
Kotlin - Null Safety
You want to safely convert a Java platform type String to uppercase in Kotlin, but the Java method may return null. Which Kotlin code is best?
Aval upper = javaApi.getName()?.uppercase() ?: "UNKNOWN"
Bval upper = javaApi.getName()!!.uppercase()
Cval upper = javaApi.getName().uppercase()
Dval upper = javaApi.getName()?.toUpperCase()
Step-by-Step Solution
Solution:
  1. Step 1: Handle possible null from Java method

    Using safe call ?. avoids NullPointerException if getName() returns null.
  2. Step 2: Provide default value with Elvis operator

    ?: "UNKNOWN" ensures upper has a valid string even if getName() is null.
  3. Final Answer:

    val upper = javaApi.getName()?.uppercase() ?: "UNKNOWN" -> Option A
  4. Quick Check:

    Safe call + default value handles platform nulls well [OK]
Quick Trick: Use ?. and ?: to safely handle nullable Java returns [OK]
Common Mistakes:
MISTAKES
  • Using !! which throws exceptions
  • Ignoring null possibility
  • Using deprecated toUpperCase()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes