Bird
Raised Fist0
Kotlinprogramming~10 mins

Non-nullable types by default in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Non-nullable types by default
Declare variable
↓
Type is non-nullable by default
↓
Assign non-null value
Yes→Works fine
No↓
Compile error: Null not allowed
↓
Use nullable type with ?
↓
Can assign null or non-null value
Kotlin variables are non-nullable by default, so you cannot assign null unless you explicitly allow it with a nullable type.
Execution Sample
Kotlin
var name: String = "Alice"
// name = null // Error: Null not allowed
var nullableName: String? = "Bob"
nullableName = null
This code shows a non-nullable String variable and a nullable String? variable, demonstrating assignment rules.
Execution Table
StepVariableTypeAssigned ValueAllowed?Notes
1nameString"Alice"YesNon-nullable variable assigned non-null value
2nameStringnullNoCompile error: cannot assign null to non-nullable
3nullableNameString?"Bob"YesNullable variable assigned non-null value
4nullableNameString?nullYesNullable variable assigned null value
💡 Execution stops because assigning null to non-nullable variable causes compile error
Variable Tracker
VariableStartAfter 1After 2After 3After 4
nameuninitialized"Alice"error (null assign)error (null assign)error (null assign)
nullableNameuninitializeduninitializeduninitialized"Bob"null
Key Moments - 2 Insights
Why does assigning null to 'name' cause an error?
Because 'name' is declared as a non-nullable String (see execution_table step 2), Kotlin does not allow null assignment to prevent null pointer errors.
How can a variable hold null in Kotlin?
By declaring the variable type with a question mark (String?), it becomes nullable and can hold null values (see execution_table steps 3 and 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens when we assign null to 'name' at step 2?
AIt works and 'name' becomes null
BCompile error occurs
C'name' becomes empty string
DProgram crashes at runtime
💡 Hint
Check execution_table row for step 2 under 'Allowed?' and 'Notes'
At which step does 'nullableName' first hold a null value?
AStep 4
BStep 2
CStep 3
DStep 1
💡 Hint
Look at execution_table rows for 'nullableName' and see when 'Assigned Value' is null
If we remove the question mark from 'nullableName' type, what changes in the execution table?
A'nullableName' can still hold null without error
B'nullableName' becomes an integer
CAssigning null to 'nullableName' would cause a compile error
DNo change in behavior
💡 Hint
Refer to key_moments about nullable types and null assignment
Concept Snapshot
Kotlin variables are non-nullable by default.
You cannot assign null to a non-nullable type.
Use '?' after type to allow null (nullable type).
Nullable variables can hold null or non-null values.
This helps avoid null pointer errors at runtime.
Full Transcript
In Kotlin, variables are non-nullable by default, meaning you cannot assign null to them. For example, a variable declared as 'var name: String' must always hold a non-null string. If you try to assign null to it, the compiler will show an error and stop the program from compiling. To allow a variable to hold null, you must declare it as nullable by adding a question mark after the type, like 'var nullableName: String?'. This variable can then hold either a string or null safely. This design helps prevent null pointer exceptions by catching null assignments at compile time.

Practice

(1/5)
1. In Kotlin, what happens if you declare a variable without a ? after its type?
easy
A. The variable cannot hold null values.
B. The variable can hold null values.
C. The variable is automatically initialized to null.
D. The variable must be declared as lateinit.

Solution

  1. Step 1: Understand Kotlin's default type behavior

    Kotlin types are non-nullable by default, meaning variables cannot hold null unless specified.
  2. Step 2: Check the effect of missing ?

    Without ?, the variable type is non-nullable, so it cannot hold null.
  3. Final Answer:

    The variable cannot hold null values. -> Option A
  4. Quick Check:

    Non-nullable type = no null allowed [OK]
Hint: No ? means no null allowed [OK]
Common Mistakes:
  • Thinking variables are nullable by default
  • Assuming variables initialize to null automatically
  • Confusing lateinit with nullability
2. Which of the following Kotlin variable declarations is correct to allow null values?
easy
A. val name: String? = null
B. val name: String?
C. val name: String = null
D. val name: String = "null"

Solution

  1. Step 1: Identify nullable type syntax

    Adding ? after the type allows the variable to hold null.
  2. Step 2: Check initialization

    Nullable variables must be initialized or declared with null explicitly, so val name: String? = null is correct.
  3. Final Answer:

    val name: String? = null -> Option A
  4. Quick Check:

    Nullable type with ? and initialized to null [OK]
Hint: Use ? and initialize nullable variables [OK]
Common Mistakes:
  • Declaring nullable without ?
  • Not initializing nullable variables
  • Assigning null to non-nullable types
3. What will be the output of this Kotlin code?
fun main() {
    val text: String? = null
    println(text?.length ?: "No text")
}
medium
A. 0
B. Compilation error
C. null
D. No text

Solution

  1. Step 1: Understand safe call operator usage

    The text?.length safely accesses length only if text is not null.
  2. Step 2: Evaluate the Elvis operator

    Since text is null, text?.length is null, so the Elvis operator ?: returns "No text".
  3. Final Answer:

    No text -> Option D
  4. Quick Check:

    Safe call + Elvis operator returns fallback [OK]
Hint: Safe call with Elvis returns fallback if null [OK]
Common Mistakes:
  • Expecting 0 instead of fallback string
  • Confusing safe call with normal call
  • Thinking code causes error due to null
4. Identify the error in this Kotlin code snippet:
fun main() {
    val number: Int = null
    println(number)
}
medium
A. Variable 'number' is not initialized.
B. Cannot assign null to a non-nullable type Int.
C. Missing semicolon after println statement.
D. Variable 'number' should be declared as var.

Solution

  1. Step 1: Check variable type and assignment

    The variable 'number' is declared as non-nullable Int but assigned null, which is not allowed.
  2. Step 2: Understand Kotlin null safety rules

    Non-nullable types cannot hold null, so this causes a compilation error.
  3. Final Answer:

    Cannot assign null to a non-nullable type Int. -> Option B
  4. Quick Check:

    Non-nullable types reject null assignments [OK]
Hint: Non-nullable types cannot be assigned null [OK]
Common Mistakes:
  • Thinking semicolon is required
  • Assuming var fixes null assignment
  • Ignoring Kotlin's null safety
5. You have a nullable variable val input: String?. You want to print its length only if it is not null, otherwise print "Empty input". Which Kotlin code correctly does this?
hard
A. println(input.length ?: "Empty input")
B. println(input!!.length)
C. println(if (input != null) input.length else "Empty input")
D. println(input?.length)

Solution

  1. Step 1: Understand nullable variable usage

    Since input can be null, we must check before accessing length.
  2. Step 2: Evaluate each option

    println(input.length ?: "Empty input") is invalid because length is Int, not nullable, so Elvis operator on it is wrong.
    println(if (input != null) input.length else "Empty input") safely checks null and prints length or fallback.
    println(input!!.length) uses !! which throws exception if null.
    println(input?.length) prints null if input is null, not the string "Empty input".
  3. Final Answer:

    println(if (input != null) input.length else "Empty input") -> Option C
  4. Quick Check:

    Explicit null check with if-else for safe access [OK]
Hint: Use if-else to check null before accessing properties [OK]
Common Mistakes:
  • Using !! and risking exceptions
  • Misusing Elvis operator on non-nullable Int
  • Printing null instead of fallback string
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard