Chapter 2. What is a variable

A variable is a location or set of locations in computer memory to store an item of data which is named by an identifier.

 

Imagine a large library with lots of shelves, tables, special rooms etc. These are the places where you can keep books. Let’s imagine I want to borrow “Thinking of Java” book and I want to know where exactly it located in the library is. I wouldn’t say that it is located 45’7” from the south wall and 14’9” from the west wall.

Likewise in programming terms, I also wouldn't say that my total fee paid last year is stored in four bytes starting at location 647,986,307,215 in RAM.

Each time the program is running, the computer will place variables in different locations in RAM. However the program knows exactly where the data is stored. The programmers do this by creating a variable to refer to it. In the library, the “Thinking of Java” book might be on section 5 of shelf 3 in the programming area under IT. In the PC, the program will know exactly where its variables are located.

Variables are temporary. Variables exist during the lifespan of the computer program and then disposed of. Variables are like numbers in a calculator. When you press the clear or power off buttons, the numbers which displayed are lost.