Skip to main content
Kotlin Basics
CHAPTER 12 Beginner

Null Safety in Kotlin

Updated: May 18, 2026
5 min read

# CHAPTER 12

Null Safety in Kotlin

1. Chapter Introduction

In 1965, Tony Hoare invented the null reference, which he later called his "Billion Dollar Mistake" because it has caused countless server crashes and application failures (the infamous NullPointerException). Java suffers heavily from this. Kotlin's primary selling point is its built-in Null Safety. Kotlin's type system is designed to eliminate the danger of null references from code. In this chapter, we will master Nullable types, Safe Calls, and the Elvis Operator.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Distinguish between Non-Null and Nullable types (?).
  • Understand why the compiler blocks null assignments.
  • Safely access properties of nullable objects using ?..
  • Provide default values using the Elvis operator ?:.
  • Understand the dangers of the Not-Null Assertion !!.

3. The Non-Null Default

By default, variables in Kotlin CANNOT hold a null value.
kotlin
12345
fun main() {
    var name: String = "Alice"
    
    // name = null // COMPILER ERROR: Null can not be a value of a non-null type String
}

Because the compiler guarantees name is never null, you can safely call name.length without ever worrying about a crash.

4. Nullable Types (?)

Sometimes, a variable *needs* to be null. (e.g., A user might not have a middle name). To allow a variable to hold null, you must explicitly declare it as a Nullable Type by adding a question mark ? to the type.
kotlin
12345
fun main() {
    var middleName: String? = "Marie" // String? means it can be a String OR null
    
    middleName = null // This is now perfectly legal!
}

5. The Compile-Time Check

Here is the magic of Kotlin: If a variable is marked as nullable (String?), the compiler WILL NOT LET YOU call methods on it directly!
kotlin
123
var middleName: String? = null

// println(middleName.length) // COMPILER ERROR: Only safe (?.) or non-null asserted (!!.) calls are allowed

The compiler mathematically prevents the Null Pointer Exception by forcing you to handle the potential null before the app even runs.

6. The Safe Call Operator (?.)

How do we get the length without crashing? We use the Safe Call operator ?. It translates to: *"If the object is NOT null, execute the method. If it IS null, skip it and return null."*
kotlin
123456789
fun main() {
    var middleName: String? = null
    
    // Safely requests the length. If null, it just returns the word 'null'.
    println(middleName?.length) // Output: null
    
    middleName = "Marie"
    println(middleName?.length) // Output: 5
}

7. The Elvis Operator (?:)

Often, we don't want to print the word "null". We want to provide a default fallback value. We use the Elvis Operator ?:. It translates to: *"If the left side is not null, use it. Otherwise, use the right side."*
kotlin
123456789
fun main() {
    var middleName: String? = null
    
    // If middleName is null, the length is safe-called as null.
    // The Elvis operator catches that null and provides 0 instead!
    val length = middleName?.length ?: 0
    
    println("Middle name length is: $length") // Output: 0
}

8. The Not-Null Assertion (!!) (DANGER!)

If you are 100% mathematically certain that a nullable variable is not null at a specific moment, you can force the compiler to treat it as non-null using the !! operator.

WARNING: If you use !! and the variable actually *is* null, the application will crash with a NullPointerException (NPE)!

kotlin
123
var name: String? = null

// println(name!!.length) // CRASH! DO NOT DO THIS!

*Rule of thumb: Try to never use !! in production code. It defeats the entire purpose of Kotlin's safety.*

9. Mini Project: Safe User Profile

Let's build a safe data processor that handles missing data elegantly.
kotlin
1234567891011121314
fun main() {
    val username: String = "AdminUser" // Guaranteed to exist
    val bio: String? = null            // Might be missing
    
    println("User: $username")
    
    // Safely print the bio or a default message
    val displayBio = bio ?: "This user has not set a biography."
    println("Bio: $displayBio")
    
    // Safely calculate length
    val bioLength = bio?.length ?: 0
    println("Bio Length: $bioLength characters")
}

10. Common Mistakes

  • Using !! to bypass compiler errors: Beginners often use !! when the compiler complains about a nullable type, just to make the red squiggly line go away. This brings Java's NPEs straight back into your code. Use ?. instead!

11. Best Practices

  • Embrace ?. and ?:: Chaining safe calls is idiomatic Kotlin. You can chain them deeply: user?.department?.manager?.name ?: "No Manager". This replaces dozens of lines of if (user != null) checks in Java.

12. Exercises

  1. 1. Declare a nullable String city and assign it null.
  1. 2. Use the safe call operator to print the uppercase version of city.
  1. 3. Use the Elvis operator to print "Unknown City" if city is null.

13. MCQs with Answers

Q1. By default, can a Kotlin variable hold a null value? a) Yes b) No, standard types are non-null by default Answer: b) No, they are non-null by default.

Question 2

How do you explicitly declare that a variable is allowed to hold null?

Question 3

If a variable is nullable (String?), why does the compiler reject name.length?

Question 4

What is the Safe Call operator?

Question 5

What does the Safe Call operator do if the variable is null?

Question 6

What is the Elvis operator?

Question 7

In val a = b ?: "Default", what happens if b is null?

Question 8

What does the Not-Null Assertion !! do?

Q9. Should you use !! frequently in production code? a) Yes, it's fast b) No, it defeats Kotlin's built-in null safety and can cause crashes Answer: b) No, it defeats null safety.
Question 10

Why is Kotlin's Null Safety considered its best feature?

14. Interview Questions

  • Q: Explain how Kotlin prevents NullPointerExceptions at compile time.
  • Q: If you have a chain like company?.ceo?.name, what happens if company is null? (Answer: The entire chain immediately evaluates to null. It does not attempt to access .ceo, preventing a crash).

15. Summary

Null safety is the crown jewel of Kotlin. By forcing developers to explicitly acknowledge when data might be missing (using ?), the compiler shifts the burden of error checking from runtime to compile-time. Mastering ?. and ?: allows you to write incredibly robust, crash-resistant applications.

16. Next Chapter Recommendation

We have mastered basic logic and safety. Now it is time to model real-world data. In Chapter 13: Classes and Objects, we will enter the world of Object-Oriented Programming (OOP) and learn how to create our own custom data types.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·