AP Computer Science Principles · Unit 3: Algorithms & Programming
3.1 Variables and Assignments
What is a variable?
A variable is an abstraction in programming used to represent a value stored in a computer's memory. Variables have a name, a value, and a data type. They allow programs to store, retrieve, and update data, avoiding the need to rewrite values repeatedly throughout code.
The assignment operator
The assignment operator (often `=` or `←`) stores a value in a variable's memory location. When a variable is assigned a new value, the previous value is overwritten (lost). Assignment statements are evaluated right-to-left: the expression on the right is computed first, then stored in the variable on the left.
Why use variables?
Variables make programs flexible and reusable — instead of hardcoding numbers, you can change one variable's value to affect the whole program. Good variable naming (descriptive names) improves readability and helps others (and you) understand what data represents, which is essential for collaboration and debugging.
Key terms
- Variable
- An abstraction used to represent a value stored in memory, having a name, value, and data type.
- Assignment operator
- The operator (e.g., `=` or `←`) used to store a value into a variable.
- Order of evaluation in assignment
- The expression on the right side is evaluated first, then the result is stored in the variable on the left.
- Why variable naming matters
- Descriptive names improve program readability and make code easier to understand, debug, and maintain.
- Effect of reassigning a variable
- The variable's previous value is overwritten and lost unless it was saved elsewhere beforehand.
Try an AP-style question
Code
a ← 3 b ← a a ← 5 DISPLAY(b)
What is displayed?
- a
- 8
- 5
- 3
Show the answer
D. b got a copy of 3.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 3.1 free in APrep