Sub topic 5
Assignment and Compound Assignment
Assignment stores a value in a variable. It lets a program keep a result and use it later. Compound assignment provides a shorter way to update a variable using its current value.
This chapter assumes you can declare Java variables and run a simple Java program.
Assigning a value
The assignment operator is =. It stores the value on its right in the variable on its left.
public class AssignmentExample {
public static void main(String[] args) {
int score = 10;
score = 15;
System.out.println(score);
}
}Save this as AssignmentExample.java, then run:
javac AssignmentExample.java
java AssignmentExampleThe output is 15. The first line inside main declares score and gives it an initial value. The next line replaces that value with 15.
The value on the right can be an expression. An expression is code that produces a value. For example, after score = score + 5;, the value of score is 20. Java calculates score + 5 using the current value, then stores the result back in score.
Updating with compound assignment
A compound assignment operator combines an operation with assignment. For example, += adds a value to the current value of a variable and stores the result.
If score is 20, both of these statements change it to 25:
score = score + 5;score += 5;
The table shows common arithmetic forms. In each row, assume amount starts at 12.
| Statement | Operation | New value of `amount` |
|---|---|---|
| `amount += 5;` | Add 5 | `17` |
| `amount -= 5;` | Subtract 5 | `7` |
| `amount *= 5;` | Multiply by 5 | `60` |
| `amount /= 5;` | Divide by 5 | `2` |
| `amount %= 5;` | Find the remainder after division by 5 | `2` |
The result of 12 / 5 is 2 here because both values are integers. An integer is a whole number, and integer division drops the fractional part.
The right side can contain more than one value. For example, if score is 4, then score += 3 * 2; changes it to 10. Java calculates 3 * 2 first, then adds the result to score.
Parentheses can make a different calculation clear. If score is 10, then score *= (1 + 2); changes it to 30.
A complete update example
The following program starts with a balance and applies several updates. It also shows that += can add text to a String. A String is a Java type used for text.
Save it as UpdateDemo.java.
public class UpdateDemo {
public static void main(String[] args) {
int balance = 20;
balance += 5;
balance -= 3;
balance *= 2;
balance /= 3;
balance %= 4;
System.out.println("Balance: " + balance);
int score = 4;
score += 3 * 2;
System.out.println("Score: " + score);
String message = "Hello";
message += "!";
System.out.println(message);
}
}Compile and run it:
javac UpdateDemo.java
java UpdateDemoThe output is:
Balance: 2
Score: 10
Hello!Follow the balance one step at a time: 20 becomes 25, then 22, then 44. Integer division by 3 gives 14. The remainder after dividing 14 by 4 is 2.
For the String, message += "!"; joins the existing text with "!" and stores the resulting text back in message.
The type of the stored value
A variable has a type, and Java checks what can be stored in it. For example, you cannot assign text to an int variable with score = "ten";.
Compound assignment has a special rule: Java converts the result back to the type of the left-hand variable. This can lose information.
Save and run this example as ConversionDemo.java:
public class ConversionDemo {
public static void main(String[] args) {
int items = 7;
items += 1.8;
System.out.println(items);
byte small = 120;
small += 10;
System.out.println(small);
}
}javac ConversionDemo.java
java ConversionDemoThe output is:
8
-126For items, the addition produces 8.8. The compound assignment converts that result to int, dropping the fractional part before storing it.
A byte is an integer type that can hold values from -128 through 127. For small, the result 130 is outside that range. The conversion wraps it to -126. This is a form of overflow: the result does not fit in the available range.
The longer form is not always accepted in the same way. For example, small = small + 10; does not compile: Java calculates small + 10 as an int, which it will not automatically store in a byte. A cast is a request to convert a value to a type. You could write small = (byte) (small + 10);, but it has the same wrapping risk.
Assignment produces a value
An assignment expression also produces the value it stores. This makes it possible to assign the same value to two variables:
public class ChainedAssignment {
public static void main(String[] args) {
int first;
int second;
first = second = 6;
System.out.println(first);
System.out.println(second);
}
}Save it as ChainedAssignment.java and run it with javac ChainedAssignment.java followed by java ChainedAssignment. Both lines of output are 6.
Java groups the assignment as first = (second = 6). The inner assignment stores 6 in second and produces 6. The outer assignment then stores that value in first.
Chaining can be useful, but separate statements are often easier to read. Use the form that makes your intention clear.
Common mistakes
- The left side must be a place Java can store a value, such as a variable.
5 = score;is not valid. - A local variable must have a value before you read it. For example,
int total;followed bytotal += 2;does not compile becausetotalhas no starting value. - A variable declared with
finalcannot be assigned a new value after it has been assigned. - Write the compound operator without a space:
+=, not+ =. - For a simple variable,
x += yusually resemblesx = x + y, but type conversion can make a difference. With more complex places to store a value, compound assignment also evaluates that place only once.
Practice
Exercise
If int total = 10; is followed by total += 4 * 2;, what is total?
Show answer
18. Java calculates 4 * 2 first, then adds 8 to 10.
Exercise
If int pieces = 9; is followed by pieces /= 2;, what value is stored?
Show answer
4. Integer division drops the fractional part.
Exercise
Why does int count; count += 1; fail to compile inside a method?
Show answer
count += 1 needs to read the current value of count, but the local variable has not been given a value yet.