5 - Variables
Learning Objectives :
- Learn what a variable is
- Learn how to declare variables
- Learn how to assign a value to variables
- Learn how to get input from the console
- Learn the difference between variables declaration and assignment
In the previous chapter we learned about some key building blocks that made up a Fantom program. Using expressions and operators we can manipulate data and make calculations. What if we want to do multiple operations on one value? What if we want save data that we use, so we can access it easily later? That's the whole point of variables.
In programming variables are storage for data. Just like in math variables may change their value. Variables can be used to store the value of an expression or just hold a literal value. InFantom variables are only allowed to hold one type of data. For example a variable that is declared to hold a string value can hold an int value. What do we mean by decaring and holding values? I will explain in the next few sections.
Declaring A Variable
Declaring a varible is just creating a variable. When variables are declared space in memory is set aside for that variable to store its data. The ammount of memory allocated for that variable depends on the type of data that variable is going to hold. To declare a new variable in Fantom you use the following syntax ;
DataType varible_name := value;
You specify what type of data a varible is going to hold by giving it a datatype. Again, datatype is the type of data a variable can hold. Some basic datatypes and what they represent are :
Int: Represents and integer. ( Positive and Negative Whole numbers )
Float: Represents a floating-point number.
Decimal: Represents a floating-point number with higher percision than
Bool: Represents a boolean value.(true or false)
Char: Represents a single character.
Str : Represents a string (array) of characters.
When you sepcify the type of data you want a varible to hold you don't have to initialize it. So for example if I knew a variable name was going to be a Str I don't need to initialize it when I declare it. I can just do :
On the contrary if I initialize a variable I can omit the DataType declaration and the datatyep will be automatically infered by the compiler. So I can do :
`age := 23; //Automatically infered to be an int.
But this is not recommended for large applications.
Notice the use of the
:= operator for variable initialization. If you have any programming experience of just find it weird. Fantom does not use the
= assignment operator to initialize varible.