0
0
Kotlinprogramming~10 mins

Var for mutable references in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Var for mutable references
Declare var x = 5
x holds value 5
Change x = 10
x now holds value 10
Use x in expressions
Program continues
This flow shows how a variable declared with var can be changed to hold different values during program execution.
Execution Sample
Kotlin
var x = 5
println(x)
x = 10
println(x)
This code declares a mutable variable x, prints its initial value, changes it, then prints the new value.
Execution Table
StepActionVariable xOutput
1Declare var x = 55
2Print x55
3Assign x = 1010
4Print x1010
5End of program10
💡 Program ends after printing updated value of x
Variable Tracker
VariableStartAfter Step 1After Step 3Final
xundefined51010
Key Moments - 2 Insights
Why can we change the value of x after declaring it with var?
Because var declares a mutable variable, so its value can be updated as shown in steps 1 and 3 of the execution_table.
What would happen if x was declared with val instead of var?
Declaring x with val makes it immutable, so trying to assign a new value like in step 3 would cause a compile error.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of x after step 3?
A5
Bundefined
C10
DError
💡 Hint
Check the 'Variable x' column at step 3 in the execution_table.
At which step is the first output produced?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Output' column in the execution_table to find when output first appears.
If we change var x = 5 to val x = 5, what happens at step 3?
Ax changes to 10
BCompile error
Cx remains 5 silently
DRuntime error
💡 Hint
Recall that val means immutable; reassigning causes a compile error.
Concept Snapshot
var declares a mutable variable in Kotlin
You can change its value anytime after declaration
Use var when you need to update the variable
val declares an immutable variable (cannot change)
Changing a var variable updates its stored value
Printing shows current value at that moment
Full Transcript
This example shows how to use var in Kotlin to create a mutable variable named x. Initially, x is set to 5. When we print x, it outputs 5. Then we change x to 10. Printing x again outputs 10. The key point is that var allows the variable to be changed after it is declared. If we used val instead, trying to change x would cause an error. The execution table tracks each step, showing the value of x and any output. The variable tracker shows how x changes from undefined to 5, then to 10. This helps beginners see how mutable variables work in Kotlin.