What's the difference between "!!" and "?" in Kotlin?

Kotlin Mobile DevelopmentApps/Applications

In this article, we will take an example and demonstrate the difference between (!!) and (?) in Kotlin.

Example – "!!" and "?" operator in Kotlin

Kotlin provides a wonderful operator to check NULL pointer exceptions. It throws a NULL pointer exception instead of breaking the programming logic whenever the variable is NULL.

In the following example, the value of "test" is NULL. Hence, Kotlin will throw a NULL pointer exception instead of breaking down the logic. The example shows the different uses of "!!" and "?" operators.

fun main(args: Array<String>) {
   val nullValue: String ?=null

   // it will print null
   println("The value is ->"+nullValue?.length)

   // it will throw the exception


On execution, it will produce the following output −

The value is ->null
Exception in thread "main" java.lang.NullPointerException
   at MainKt.main(main.kt:8)

The following table sums up the difference −

Input is nullnullNull pointer exception
Updated on 01-Mar-2022 10:38:44