Sub topic 5
Assignment and Compound Assignment
A variable is a named place to store a value. An assignment stores a value in a variable. In Java, the assignment operator is =.
An operator is a symbol that tells Java to perform an action. An expression is code that produces a value. In points = points + 3, the expression on the right produces the value to store.
Assigning a value
An int variable stores a whole number. This line creates an int variable named points and gives it a starting value:
int points = 10;
You can then change its value with an assignment:
points = points + 3;
For a simple variable, Java calculates the value on the right before storing it. If points was 10, the expression points + 3 produces 13. The assignment then stores 13 in points.
The = symbol does not mean “is equal to” in this statement. It means “store the value on the right in the variable on the left.”
Updating with compound assignment
Compound assignment combines an operation with assignment. For example, points += 3 adds 3 to the current value of points and stores the result back in points.
The table shows common forms. Each result assumes points starts at 10.
| Statement | What it does | Stored result |
|---|---|---|
| `points += 3;` | Adds `3` | `13` |
| `points -= 3;` | Subtracts `3` | `7` |
| `points *= 3;` | Multiplies by `3` | `30` |
| `points /= 3;` | Divides by `3` | `3` |
| `points %= 3;` | Finds the remainder after division by `3` | `1` |
With int values, division drops the fractional part. That is why 10 / 3 gives 3.
Try it
Save this program as AssignmentDemo.java, then run it:
public class AssignmentDemo {
public static void main(String[] args) {
int points = 10;
points = points + 3;
System.out.println(points); // 13
points += 2;
System.out.println(points); // 15
points *= 2;
System.out.println(points); // 30
points -= 4;
System.out.println(points); // 26
points /= 3;
System.out.println(points); // 8
points %= 4;
System.out.println(points); // 0
}
}Each statement uses the value stored by the previous statement. For example, points *= 2 uses 15, not the original 10.
Common mistakes
- Give a local variable a value before using it in a compound assignment. For example,
int points; points += 3;does not compile becausepointshas no value yet. - Do not assume compound assignment is always identical to writing the longer form. Java can automatically convert the result of a compound assignment to the variable’s type. For example,
int n = 5; n += 2.5;stores7, butn = n + 2.5;does not compile. Avoid mixing types until you understand the conversion. - An assignment is also an expression: its result is the value stored. For clarity, it is usually best to put an assignment on its own line.
Exercise
If int score = 11; is followed by score -= 3; and then score *= 2;, what is stored in score?
Show answer
16. The subtraction stores 8, and the multiplication then stores 16.