Loading lessons...
Changing Variable Values
Changing Variable Values
Variables are called variables for a reason: you can change them.
Reassign a value
int myNum = 15;
myNum = 10; // myNum is now 10
Reassign from another variable
int myNum = 15;
int myOtherNum = 23;
myNum = myOtherNum; // myNum becomes 23
Copying is one-way
When you do myNum = myOtherNum, you copy the value. Changing myOtherNum later does NOT change myNum.
int a = 5;
int b = a; // b is 5
a = 100; // a is 100, but b is still 5
Overwriting
Each assignment replaces the old value completely. The previous value is gone.
TL;DR
- Assign a new value:
myNum = 10;. - Copy another variable:
myNum = myOtherNum;. - Copies are one-way; later changes don't flow back.
- The old value is lost when overwritten.