AP® Computer Science A · Unit 1 · Topic 1.4
Assignment Statements and Swapping Two Values
An assignment statement evaluates everything on the right side first, using the current values, then dumps that single result into the variable on the left. The equals sign is an instruction to store, not a claim that two things are equal.
Java's = does one job: evaluate the right side completely, then copy that result into the variable on the left. That is why x = x + 1 is normal code instead of nonsense. The right side, x + 1, is computed using x's current value, say 5, giving 6. Only after that computation finishes does Java overwrite x with 6. Nothing is claimed to be equal to anything; a value is just moved into a box.
This order of operations explains why a = b; b = a; does not swap two variables. Say a is 5 and b is 8. The line a = b; evaluates b, which is 8, and stores it into a. Now a is 8 and the original 5 is gone forever. The next line, b = a;, evaluates a, which is already 8, and stores it into b. Both variables end up holding 8, and the original 5 vanished with no way to recover it. To actually swap, you need a third variable to hold one value temporarily: int temp = a; a = b; b = temp; Now temp rescues a's original value before a gets overwritten, so b can safely grab it on the last line.
This is the moment to stop reading = as the algebra symbol and start reading it as 'store into.' Every assignment statement you write for the rest of the course, including ones involving objects and references, follows this same two-step rhythm: evaluate the whole right side first, then overwrite the left.
Key terms
- assignment statement
- A statement that evaluates the expression on the right of = and stores the resulting value into the variable on the left.
- right-side evaluation
- The rule that Java computes the entire right-hand expression using current values before any storing happens.
- overwrite
- Replacing a variable's previous value with a new one, permanently losing the old value unless it was saved elsewhere.
- temporary variable
- An extra variable used to hold a value briefly so it is not lost when another variable gets overwritten.
Watch it explained
- How it worksHow does an assignment evaluate the whole right side first and then overwrite the left?
- Worked exampleTrace int a = 5, b = 8; a = b; b = a; and find why both variables end up holding 8.
- How it worksWalk me through swapping two variables correctly using a third temporary variable.
- Common mistakeWhy isn't the equals sign in Java a claim that two things are the same?
Check yourself
End of topic.