What is Null Safety in Kotlin?

// Quick Answer
  • Null safety prevents NullPointerException errors.
  • Kotlin distinguishes between nullable and non-nullable types.
  • It uses ?, !!, and safe calls to handle nulls safely.
  • Null checks are enforced at compile time.
  • It makes Kotlin safer than Java in handling null values.

What is null safety in Kotlin?

Null safety in Kotlin is a feature that helps prevent errors caused by null values. In many languages like Java, accessing a null value causes a runtime crash. Kotlin avoids this by handling nulls at compile time.

💡 Simple idea

Kotlin forces you to explicitly decide whether a variable can be null or not — reducing unexpected crashes.

Nullable vs Non-nullable types

In Kotlin, variables are non-nullable by default. This means they cannot hold null unless you explicitly allow it.

Kotlin
var name: String = "John"
name = null // ❌ Error

To allow null values, you must use the ? symbol:

Kotlin
var name: String? = "John"
name = null // ✅ Allowed

Safe call operator (?.)

The safe call operator ?. allows you to access properties safely without crashing.

Kotlin
val name: String? = null

println(name?.length) // prints null instead of crashing

Elvis operator (?:)

The Elvis operator provides a default value when something is null.

Kotlin
val name: String? = null

val length = name?.length ?: 0

println(length) // 0

Not-null assertion (!!)

The !! operator forces Kotlin to treat a value as non-null. If it is null, your app will crash.

Kotlin
val name: String? = "Kotlin"

println(name!!.length) // use carefully

Why null safety matters

  • 🛡️ Prevents NullPointerException crashes
  • ⚙️ Forces safer code design
  • 📘 Improves readability and clarity
  • 🚀 Reduces runtime bugs
  • 👥 Helps large teams avoid hidden errors
📌 Real-world fact

Null pointer exceptions are one of the most common crash reasons in Java apps. Kotlin was designed specifically to eliminate this class of bugs.

Summary

Null safety in Kotlin ensures that null values are handled explicitly and safely. With nullable types, safe calls, and operators like ?:, Kotlin prevents many common runtime crashes.

In short: Kotlin makes null errors a compile-time problem instead of a runtime disaster.