๐1.6: Compound Operators
Table of Contents
๐ This page is a condensed version of CSAwesome Topic 1.6
Compound Assignment Operators
๐ฌ As a class, brainstorm some examples of how people use shortcuts.
Compound assignment operators +=, -=, *=, /=, and %= are shortcuts that do a math operation and an assignment in one step.
For example,
x += 1adds 1 toxand stores the result back inx(same asx = x + 1).
If a mnemonic helps: the operator happens first, then the result is assigned back. So itโs += (not =+).
Since changing a variable by 1 is so common, Java also has ++ (increment) and -- (decrement) extra concise operator.
x++is even shorter thanx += 1orx = x + 1.y--is the same idea for subtracting 1.
Operator Shortcuts
| Meaning | Written out | Compound | Extra Concise |
|---|---|---|---|
| add | x = x + 1 | x += 1 | x++ |
| subtract | x = x - 1 | x -= 1 | x-- |
| multiply | x = x * 2 | x *= 2 | โ |
| divide | x = x / 2 | x /= 2 | โ |
| remainder | x = x % 2 | x %= 2 | โ |
Type each of these lines, run, and observe. Then complete the two TODOs.
int score = 0;
System.out.println(score); // 0
score++; // +1
System.out.println(score); // 1
score *= 2; // ร2
System.out.println(score); // 2
int penalty = 5;
score -= penalty / 2; // 2 - (5/2) -> 2 - 2 -> 0 (integer division)
System.out.println(score); // 0
// 1) Add 3 to score using a compound operator
// score ...
// 2) Divide score by 2 using a compound operator
// score ...
Code Tracing
Code tracing means simulating a run through the program line by line, as if you are the computer.
Use a trace table (or bullet points) to track variable values as they change and predict output.
๐ฎ Predict: What are the values of x, y, and z after this code?
int x = 0;
int y = 1;
int z = 2;
x--;
y++;
z += y;
๐ฎ Predict: What are the values of x, y, and z after this code?
int x = 3;
int y = 5;
int z = 2;
x = z * 2;
y = y / 2;
z++;
Try the Operators Maze game: Operators Maze game.
Summary
- (AP 1.6.A.1) Compound assignment (
+=,-=,*=,/=,%=) performs the operation using the current value on the left and the value on the right, then assigns the result back to the left variable. - (AP 1.6.A.2) Increment (
++) and decrement (--) add or subtract 1 from a numeric variable and store the new value.
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.