We have two variables under our belt and it's time we group them into a variable type. This is a critical concept that we will revisit as we learn what objects are, but for now it's good for us just to understand that we have a different type of variable. A few new topics we are about to learn are dependent upon the logic that this only works for primitive values. (Have no clue what primitive values are, well jump in and let's figure it out!)
We can describe primitive variables as the containers that store data for a time. These variables don't preserve large amounts of data to be used later. In other words, we can say that these are instant variables. As said earlier, the concept is clearly understood when compared with objects. Objects are created using classes: these objects are used to store buckets of information at a time. In the case of primitive variables, only one value at a time can be assigned to a primitive variable. If you assign another value to this variable, the variable now contains the new value and the old value is gone.
For example let's declare a variable num and assign a value 5 to it: var num:int=5; . Now, according to the definition of this variable, num=5. If we use num in any part of the program, the compiler assumes this as the integer 5. So let's now assign another value, 10, to the same variable num: num=10;. We would expect num to have both the values 5 and 10. But once you assign a new value to a primitive variable, the new value overrides the old value – the variable now contains the new value and not the old one. The variable always contains the most recent value and all the old values are erased. Therefore, these variables are considered as primitive variables. So the value of num is now equal to 10 (num=10.)
Now we'll consider another example. If we declare a variable a and assign a value 3 to it, we can say that a=3. In the next line, declare another variable b and assign a to it:
var a: int = 3;
var b: int = a;
At first glance, we think b = a, but this is not always the case! In fact, b takes the initial value of a, 3: a=3 then b=a so b now equals 3.
For extra credit: later on in your code, you change the value of a: a = 420. What does b equal now? If you said 420, beep! b still equals 3. Primitives hold their initial values until changed: you'd need to add the line b=a; again if you wanted b to have a's NEW value.
These types of conversions are performed with primitive variables. The knowledge of primitive variables is necessary before you start dealing with objects.
Have a question but don't want to ask it publicly? If you are a prime member just ask right here and we will get back to you within 48 hours. Not prime yet? no worries you can ask publicly below.