AP® Computer Science Principles · Big Idea 3 · Topic 3.1

Variables and Assignment

A variable is a named storage location that holds a value. An assignment statement computes the right-hand side first, then stores that result in the variable, overwriting whatever was there.

A program needs named boxes because it works with values that change or that get reused. Writing the number 5 directly into your code means you're stuck with 5 forever. Storing it in a variable called score or total means the same line of code can work no matter what value the variable currently holds. The name also makes code readable: total makes sense to a human in a way that a bare 5 scattered through the program never does.

Every assignment statement works the same way, in two steps, in order. First the computer evaluates the entire right-hand side using whatever values the variables currently hold. Only after that result is fully computed does it get copied into the variable on the left. This matters because the variable being assigned can appear on both sides. When a is set to a plus 3, the computer reads a's old value, adds 3, and only then overwrites a with the new total. The old value is gone the instant the new one is stored; a variable holds exactly one value at a time.

This two-step rule is why copying one variable into another does not create a lasting link between them. It also sets up everything that comes next in the unit: loops repeat an assignment statement many times, building up a running total or counter one step at a time, and procedures use variables to pass values in and out. Get comfortable with assignment now, because every loop trace and procedure trace afterward is really just this same copy-after-evaluate rule happening over and over.

Key terms

Variable
A named storage location in a program that holds a value which can change over time.
Assignment statement
An instruction that evaluates an expression and stores the resulting value in a variable.
Right-hand side
The expression in an assignment statement that gets fully evaluated before anything is stored.
Overwrite
To replace a variable's current value with a new one, erasing the old value permanently.

Watch it explained

  1. How it worksHow does an assignment statement evaluate the right hand side first and then store a copy?
  2. Worked exampleTrace what a holds after a is set to 5, then a is set to a plus 3, then a is set to a times 2.
  3. Common mistakeWhy doesn't setting b to a mean that b keeps changing whenever a changes later on?
  4. Going furtherWhat changes about a program when a variable name says what it holds instead of just being x?

Check yourself

Your turn1 of 2
A variable a is set to 7. Then a is set to a plus 7. Then a is set to a times 6. What value does a hold now?

End of topic.