AP® Computer Science A · Unit 1 · Topic 1.2

Variables as Named Boxes in Memory

A variable is a single labeled spot in memory that holds exactly one value at a time. Declaring it reserves the spot; each assignment overwrites whatever was there before.

Programs need names for values because code has to refer to data without knowing the exact number in advance. Instead of writing 95 everywhere a test score matters, you write score, and the program looks up whatever is currently stored there. This makes code readable and lets the same instructions work with different data each time they run.

When you write int score = 0, two things happen. The declaration int score tells the program to set aside a labeled spot in memory sized for an int, and the = 0 immediately stores the value 0 in that spot. If you then write score = 10, the program does not find a new spot. It goes to the same labeled location and replaces 0 with 10. Write score = 25 next, and 10 is gone, replaced by 25. The box has one compartment. A new assignment does not add to it, it overwrites it.

This is why a variable is not a history log. People new to this sometimes picture score as remembering 0, then 10, then 25, like a list. It does not. At any instant, a variable names exactly one storage location holding exactly one value, and that value is whatever was assigned most recently. This idea matters immediately once you start evaluating expressions and tracing method calls, because every time you see a variable's name, you need to know precisely what single value sits there right now, not what it used to hold.

Key terms

variable
A named storage location in memory that holds one value of a declared type at a time.
declaration
The statement, such as int score, that reserves a labeled spot in memory for a variable.
assignment
An operation using = that stores a new value in a variable's memory spot, overwriting the old one.
overwrite
The replacement of a variable's current value with a new one, erasing the previous value.

Watch it explained

  1. How it worksHow does declaring int score = 0 set aside a spot in memory with a label stuck on it?
  2. How it worksWalk me through what happens in memory when one variable is declared and then assigned twice.
  3. Common mistakeWhy isn't a variable a container that remembers every value you ever put in it?
  4. Going furtherWhat happens when you try to use a local variable before anything has been stored in it?

Check yourself

Your turn1 of 2
int score = 35; score = 33; System.out.println(score); What does this print?

End of topic.