Anna Wierciak

Remember how programming is all about manipulating numbers? We discussed it in About Computers lesson. And numbers are stored in memory, at certain addresses.

It turns out that allocating memory to programs – for example, making sure that if your program uses addresses 100 and 101 no one else is using these addresses at the same time (your computer runs hundreds of programs simultaneously!) is quite a bit of work, and it’s something that is done by your operating system (Windows, iOS, Linux).

Higher level programming languages such as Java also contribute to making manipulating numbers easier. When you write your program you can write something like this:

int i = 5;

…and the compiler will make sure that there is a place in memory (for example, at address 101) and it’s the right size to contain a whole number of the right size, and number 5 is in that memory.

“i” is the name of that memory location which is used so programmer can refer to it without knowing or caring that it is actually 101 – and in different computers and at different times the actual location can change, but the program which uses “i” to call it doesn’t have to change.

Why is this called a variable? Because the actual context at this memory location can vary. Remember, memory can be read AND written! So a programmer can write something like this:

int i = 5;
int j = i * i * i;
System.out.println(j);
i = 6;
j = i * i * i;
System.out.println(j);

The memory location called “i” first has 5 in it. Then computer reads it, multiplies it by itself 3 times, stores the result at a memory location called “j”, and prints it (“j”) out.

THEN something interesting happens. We write 6 into the memory location that we refer to as “i”. Even though that location used to contain 5, it will, starting from line 4 of the program above, contain 6.

Then the program reads “i” again, multiplies it by itself 3 times, and stores the new value (6 cubed) into “j”. “j” now contains the new value, which the program now prints.


Exercise

Take the code from the snippet above and replace the line that prints “Hello, World!” in your Eclipse program with it (it should go between the curly braces).

Then run it. What happened?