Menu
Coddy logo textTech

What Is Null Safety

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 12 of 93.

In many programming languages, one of the most common errors is trying to access something that doesn't exist: a null value. This happens when a variable holds "nothing" instead of actual data.

Imagine asking for a user's name, but they never provided one. If your code tries to use that empty name without checking first, your program crashes. This type of bug is so common it's been called the "billion-dollar mistake."

Kotlin's Solution: Null Safety

Kotlin was designed to eliminate these crashes. By default, variables in Kotlin cannot hold null values:

fun main() {
    var name: String = "Alice"
    name = null  // Error! Won't compile
}

The compiler catches this problem before your code even runs. This is what makes Kotlin "null safe": the language itself prevents you from accidentally using null where it shouldn't be.

In the upcoming lessons, you'll learn how Kotlin lets you work with values that might be null when you actually need them, while still keeping your code safe from crashes.

challenge icon

Challenge

Easy

Declare two non-nullable variables to demonstrate Kotlin's null safety:

  • A String variable named username with the value "Kotlin"
  • An Int variable named score with the value 100

Then print both values on separate lines using println().

Remember: In Kotlin, regular (non-nullable) types cannot hold null values. The compiler ensures your variables always contain valid data.

Try it yourself

fun main() {
    // TODO: Write your code below
    // Declare a non-nullable String variable named 'username' with value "Kotlin"
    
    // Declare a non-nullable Int variable named 'score' with value 100
    
    // Print both values on separate lines using println()
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground