Variables are a key element to programming, and every programmer must understand them and how to use them. Variables are a way of storing, retrieving and modifying data within a computer program. There are two overarching types of variables; primitives and data structures. A variable is used to store any information needed by the program that is being executed, such as; a user’s name, the temperature of a kettle, the channel number of a television, etc.
A variable is stored within the computer’s memory when declared. Declaring a variable is when you create it and initilising a variable refers to the first time you assign the variable with a value. A variable that stores someone’s name is declared when you call a variable a name, and then initilised when you set the value of the variable to the person’s name, you can declare and initilise variable seperately or at the same time.
Primitive variables only assign one location in the computer’s memory, whereas data structures assign multiple values within the computer’s memory. a single number, or integer variable, such as the number ‘2’ would be a primitive variable whereas a list of integers would be a data structure. There are four main types of primitive variables; whole numbers or integers such as 2, decimal numbers or floats such as 2.5, booleans that can be ‘true’ or ‘false’, and characters that are a single unicode character such as ‘d’ or ‘1’. Characters can be single numbers too, but they are not treated as traditional numbers within a program or code. Some of these primitive, such as integers and floats, have minimum and maximum values, and there are other primitive types with bigger/smaller bounds. Choosing the correct primitive type usually comes down to the amount of memory you want to use.
Variables do not contain values themselves, they only point to where the values are stored within memory. Thinking of a street of houses can help visualise how variables and memory relate. Each primitive variable can point to any one house in the street, multiple variables can point to the same house. The house represents the memory of the computer, and within the house is where the value exists. A data structure points to multiple houses, or multiple locations in memory where values are stored.
Primitive Variables Types
|Name||Size (bits)||Minimum Value||Maximum Value||Example Values|
|byte||8||-128||1^27||-65, 32, 17|
|char||16||0||2^16-1||65, 32, 17|
|short||16||-2^15||2^15-1||-65, 32, 17|
|int||32||-2^31||2^31-1||-65, 32, 17|
|long||64||-2^63||2^63-1||-65, 32, 17|
|float||32||2^-149||(2-2^-23)·2^127||-65.0, 32.7, 17.25|
|double||64||2^-1074||(2-2^-52)·2^1023||-65.0, 32.7, 17.25|
|boolean||—||—||—||‘true’ or ‘false’|