Introduction to Variables
Variables are data containers and are essential for even the simplest programs. You store data in variables, which can then be used throughout the program. In fact, variables in programming are very similar to variables in mathematics. If you understand basic algebra then you’re already halfway there. For example, if x = 10, then what does x + 5 equal?
If x = 10
Then x + 5 = 15
Substituting x for 10 gives 10 + 5 so the answer is 15. In that example we have a variable called x, which represents the number 10. In programming, we say x is the name of the variable and 10 is the value.
Let’s do another one. If a = 7 and b = 19, then what is b – a?
If a = 7, b = 19
Then b – a = 12
In this one we have two variables called a and b that have the values 7 and 19, respectively. Therefore, b – a means 19 – 7, so the answer is 12.
However, variables don’t have to be single letters. They can be words, too. For example, if violin = 2 and bullfinch = 8 then what is violin * bullfinch? (The * means multiply in programming.)
If violin = 2, bullfinch = 8
Then violin * bullfinch = 16
The answer is 16.
Variables in Java
Now let’s see how to use variables in Java. What we have covered above is nearly valid Java already. For example, we can write x = 10
in the main method:
public static void main(String[] args) { x = 10; }
A semicolon is also needed to end the statement. However, this code will give us an error because we still need one more thing for Java to recognise x
as a variable. We need to specify what type of variable x
is. What do I mean by type? Well, 10 is a number. Specifically, 10 is an integer (a whole number). So, we need to write int
at the beginning as this tells Java that x
is an int
(integer) variable:
public static void main(String[] args) { int x = 10; }
This means that x
can only hold an integer and no other type of data, not even a fraction.
Note: We often say that variables contain, store, or hold a value because Java reserves a tiny amount of space in memory for the variable’s value.
If you were to run the program now, not much would happen. The code int x = 10;
creates a variable but that’s all. So, on the next line let’s do something with x
, like print it:
public static void main(String[] args) { int x = 10; System.out.print(x); }
[Run] 10
Again, statements are executed top-to-bottom. So, first, on line 2, a variable called x
is created with a value of 10. On line 3, x
is passed to System.out.print
to be printed. Note that the variable itself doesn’t get passed, but rather its value. Therefore, when the program is run, 10 is printed to the console. Line 2 is an example of a variable declaration; we declare (create) a variable called x
. It’s also an example of a variable initialisation, which is when a variable is a given an initial value (we give x
an initial value of 10). We can also split these two actions over two lines, like so:
public static void main(String[] args) { int x; x = 10; System.out.print(x); }
Line 2 declares variable x
. Line 3 initialises/sets x
to 10. Notice how we don’t need to write int
before x
on line 3. This is because you only need to specify the variable’s type once—at the point of declaration (line 2). From then on, you can use the variable solely by referring to its name i.e. x
.
Uninitialised Variables
In Java, you cannot use/read an uninitialised variable. In other words, you cannot use/read a variable that has not been given a value. For example, the following program won’t work:
public static void main(String[] args) { int x; System.out.print(x); }
On line 2, x is declared but not given a value. Line 3 is the offending line as it attempts to print x
when it has no value. Running the program will result in an error with the message “Variable ‘x’ might not have been initialized”.
Variable (Re)assignment
When a variable is declared and assigned a value, it is not stuck with this value. It can be reassigned different values throughout the program. For example:
public static void main(String[] args) { int x = 10; System.out.println(x); x = 8; System.out.println(x); x = -21; System.out.println(x); }
[Run] 10 8 -21
Like before, line 2 declares variable x
and initialises it to 10. Line 3 then prints x
(10). Line 4 sets x
to a different value i.e. 8. Line 5 prints x
(8). Line 6 sets x
to -21. Line 7 prints x
(-21). Notice again how you don’t need to write int
before the variable on lines 4 and 6. It’s only at the point of declaration that this is required (line 2). In general, giving a variable a value is called a variable assignment, which is why the equals (=) is called the assignment operator since it’s used for assigning values to variables.
Variable Arithmetic
You can perform arithmetic with variables. Let’s add 25 to x
.
public static void main(String[] args) { int x = 10; System.out.print(x + 25); }
[Run] 35
Line 3 does 10 + 25 to get 35, and then System.out.print
simply prints that result.
Multiple Variables
You can declare as many variables as you like. Take a look at the following program (the main
method has been omitted for brevity):
int x = 12; int y = 7; int z = x + y; System.out.print(z);
Line 1 declares a variable called x
and sets it to 12. Line 2 declares another variable called y
and sets it to 7. Line 3 declares another variable called z
but this time it gets assigned the result of x + y
. When you do this sort of thing, the right side of the equals is always calculated before the assignment takes place. So, x + y
is the same as 12 + 7
, which equals 19. Therefore, z
is set to 19. Line 4 then simply prints z
, so the output is:
(Run) 19
Order Matters
The order in which variables are declared matters. Taking the previous example, let’s try swapping the declaration of variables y
and z
.
int x = 12; int z = x + y; int y = 7; System.out.print(z);
This won’t work because we’re trying to add x
and y
on line 2, but y
won’t be declared until line 3, and you cannot use a variable that hasn’t been declared yet. It’s like trying to use something that doesn’t exist yet, it doesn’t make sense.
Basic Operations
So far, we’ve used addition +
but we can also subtract, multiply, and divide. The following table shows the symbol for the four basic operations.
Operation | Operator |
---|---|
Addition | + |
Subtraction | – |
Multiplication | * |
Division | / |
Here’s a program that applies all these operations.
int x = 13 + 2; int y = x / 3 + 1; int z = x - 8 * y; System.out.print(z);
See if you can work out what the output of the program will be when run (solution below).
On line 1, it first adds 13 + 2 to get 15, therefore:
x = 15
On line 2, we have y = x / 3 + 1. We know x = 15, therefore:
y = 15 / 3 + 1
y = 5 + 1
y = 6
On line 3, we have x – 8 * y. We know x = 15 and y = 6, therefore:
z = 15 – 8 * 6
z = 15 – 48
z = -33
Line 4 simply prints z
so the output is:
(Run) -33
Brackets
We can affect the order of operations by using brackets/parentheses. For instance, using the same program from above, on line 3 we can surround part of the expression with brackets to get a different result:
int x = 13 + 2; int y = x / 3 + 1; int z = (x - 8) * y; System.out.print(z);
(Run) 42
x
still evaluates to 15 and y
to 6 but this time z
is different due to the brackets:
z = (15 – 8) * 6
z = 7 * 6
z = 42
Dividing Two Integers
There is a big gotcha when dividing two integers because Java performs something called integer division. If two integers don’t divide evenly and result in a fraction like 4.83 then Java will truncate (shorten) the number by cutting off everything after the decimal point. For example, in reality 31 / 8 is 3.875 but in Java 31 / 8 is 3 because the .875 will be discarded. Essentially, dividing two integers will result in an integer. We can see this for ourselves:
System.out.print(31 / 8);
(Run) 3
We’ll look at what can be done about this shortly.
Space for an int
?
I mentioned before that variables take up memory. An int
variable will always occupy the same amount of space, regardless of its value. This is typically 4 bytes of memory. That means there’s a limit to the range of numbers an int variable can hold. 4 bytes is 32 bits meaning there’s 232 (4,294,967,296) different values that can be represented. By default, Java variables are signed, meaning they can hold negative numbers as well as positive numbers. Therefore int
variables can hold a maximum integer of 231 – 1 (2,147,483,647) and a minimum integer of -231 (-2,147,483,648). To illustrate, Figure 5‑1 shows the maximum possible integer an int variable can hold:
In the figure below, the number has increased by 1, which takes it over the maximum, resulting in an error:
Note
Technically, the error is popping up because Java interprets the integer number itself as an int
data type and determines that it is too large, not necessarily because we’re trying to store it in an int
variable.