Assignment Statements
How the assignment operator stores values: evaluate the right side, then store it on the left. Tracing changes step by step, why the order of assignments matters, type compatibility, and what null means for reference variables.
The assignment operator = allows a program to initialize or change the value stored in a variable. The value of the expression on the right is stored in the variable on the left. During execution, the expression is evaluated to produce a single value, and that value has a type determined by the expression. Every variable must be assigned a value before it can be used, the value must come from a compatible data type, and reference variables can be assigned a new object or the special literal null, which means no object at all.
1The Assignment Operator
An assignment statement has a variable on the left, the assignment operator = in the middle, and an expression on the right: score = 90;. It replaces whatever value the variable held with the value of the expression. The first time a variable is assigned a value, the variable is initialized; later assignments change it.
The left side must be a variable, because it names a storage location. 90 = score; does not compile: a literal cannot store anything. The right side can be any expression of a compatible type: a literal, another variable, a calculation, or a method call that returns a value.
Despite the symbol, assignment is not a statement of equality. In mathematics, x = x + 1 is an equation with no solution. In Java, x = x + 1; is an instruction: take the value in x, add 1, and store the result back in x. Reading = as "gets" or "becomes" avoids the confusion. Equality comparison uses a different operator, ==, which tests two values without changing either.
= sign in Java means "store the value on the right into the variable on the left." Read it as "gets" or "becomes," not "equals."| Statement form | What happens | Example |
|---|---|---|
type name = expression; | Declares the variable and initializes it | int laps = 4; |
name = expression; | Evaluates the expression and replaces the stored value | laps = laps + 1; |
ref = new ClassName(...); | Stores a reference to a newly created object | title = new String("Hi"); |
ref = null; | The reference variable refers to no object | title = null; |
2Evaluate, Then Store
Every assignment happens in two steps. First, the entire expression on the right side is evaluated using the values variables hold at that moment. Second, the single resulting value is stored in the variable on the left, overwriting what was there. Because the evaluation finishes before the store happens, a variable can safely appear on both sides: total = total + price; reads the old total, adds the price, and only then replaces the total.
This two-step rule explains the most common assignment patterns. Accumulating a sum uses sum = sum + value;. Counting uses count = count + 1;. Doubling uses size = size * 2;. In each case the new value depends on the old one, and the order of evaluation guarantees the old one is used.
Updating a Running Total
A savings tracker starts at 50 and adds three deposits. Predict the final balance.
int balance = 50;
balance = balance + 20;
balance = balance + 35;
balance = balance - 10;
System.out.println("Balance: " + balance);
Balance: 95
- 1Read each line as "becomes." balance becomes 50 + 20 = 70, then 70 + 35 = 105, then 105 − 10 = 95.
- 2The pattern.
variable = variable + amount;is the standard way to accumulate a total. It works because the right side is fully evaluated with the old value before the new value is stored.
| Statement | balance |
|---|---|
| int balance = 50; | 50 |
| balance = balance + 20; | 70 |
| balance = balance + 35; | 105 |
| balance = balance - 10; | 95 |
Treating a = b; as a fact that a and b are equal forever leads to wrong traces. It copies the current value of b into a once. If b changes later, a does not follow it. Primitive variables hold independent copies of values.
3Tracing a Sequence of Assignments
Statements execute one at a time, so the effect of a sequence of assignments depends on their order. The reliable way to predict the result is a trace table: one column per variable and one row per statement, recording every variable's value after each statement runs. Only the variable on the left of the assignment changes; every other value is copied down unchanged.
Trace tables make two common situations clear. When an earlier assignment changes a variable, every later statement that reads that variable sees the new value. And when a value is overwritten, it is gone for good unless it was copied somewhere first, which is why swapping or rotating values requires a temporary variable.
A Trace Table for Four Assignments
Trace a, b, and c, then predict the output.
int a = 4;
int b = a * 3;
a = b - a;
int c = a + b;
System.out.println(a + " " + b + " " + c);
8 12 20
- 1
int a = 4;a is 4. - 2
int b = a * 3;uses the current a (4): b is 12. - 3
a = b - a;uses the current values 12 and 4: a becomes 8. The old 4 is gone. - 4
int c = a + b;uses the new a (8) and b (12): c is 20.
8 12 20, matching Figure 3. Each assignment reads the values stored at that moment.When the Order of Assignments Matters
Two programs contain the same assignments in different orders. Predict both outputs.
int x = 2;
int y = 5;
x = x + y;
y = x * 2;
System.out.println(x + " " + y);
7 14
int x = 2;
int y = 5;
y = x * 2;
x = x + y;
System.out.println(x + " " + y);
6 4
- 1Program A. x becomes 2 + 5 = 7; then y becomes 7 × 2 = 14.
- 2Program B. y becomes 2 × 2 = 4 first; then x becomes 2 + 4 = 6.
- 3Why they differ. Each assignment uses whatever values exist when it runs, so changing the order changes which values are used.
7 14 and Program B prints 6 4. Same statements, different order, different results.Rotating Three Values
Three players hold positions first = 10, second = 20, and third = 30. Rotate them so that first gets second's value, second gets third's, and third gets first's original value.
int first = 10;
int second = 20;
int third = 30;
int saved = first;
first = second;
second = third;
third = saved;
System.out.println(first + " " + second + " " + third);
20 30 10
- 1Save the value that will be overwritten first.
firstis replaced before its value is needed again, so copy it tosaved. - 2Shift the others.
first = second;thensecond = third;move values along. - 3Finish with the saved value.
third = saved;places the original 10.
20 30 10. Like a swap, a rotation needs one temporary variable to protect a value before it is overwritten.In a = b; b = a;, the second statement does not restore a's original value, because a was already overwritten. Whenever a value will still be needed after its variable is reassigned, save it in a temporary variable first.
4Every Expression Has a Type
During execution, an expression is evaluated to produce a single value, and the value of an expression has a type based on the evaluation of the expression. 7 + 8 is the int 15; 15 / 2 is the int 7; 15 / 2.0 is the double 7.5; "Lap " + 3 is the String "Lap 3".
The variable receiving the value does not influence how the expression is evaluated. If the expression produces an int and the variable is a double, the finished int value is widened as it is stored, but any fraction lost during the calculation is not recovered. Work out the type of the right side on its own first, and only then think about storing it.
The same idea applies to text. In String label = "Lap " + 3 + 1;, the right side is evaluated left to right as concatenation, producing "Lap 31", and that String is what gets stored. Whatever the expression, the process is identical: evaluate it completely, determine the single value and its type, and then store that value. Assignment never looks inside the expression to change how it was computed.
Because each assignment produces one stored value, complicated calculations are often clearer when broken into several assignments with descriptive variable names, such as subtotal, tax, and total. Each intermediate variable can then be printed or traced on its own, which makes errors much easier to find than in one long expression.
The Value Has a Type Before It Is Stored
A program computes the average of 7 and 8. Predict what is stored and printed.
int sum = 7 + 8;
double avg1 = sum / 2;
double avg2 = sum / 2.0;
System.out.println(avg1);
System.out.println(avg2);
7.0
7.5
- 1
sum / 2. Both operands areint, so the expression's value is theint7. Only then is it stored in thedoublevariable, becoming 7.0. - 2
sum / 2.0. One operand is adouble, so the expression's value is 7.5, which is stored as is. - 3Principle. During execution, an expression is evaluated to produce a single value, and that value has a type determined by the expression, not by the variable that will store it.
avg1 holds 7.0 and avg2 holds 7.5. The variable's type cannot rescue a value that was already computed as an int.5Compatible Types and Initialization
Every variable must be assigned a value before it can be used in an expression, and that value must be from a compatible data type. An int value can be stored in a double variable, because widening loses nothing. A double value cannot be stored in an int variable without an explicit cast, because the fractional part could be lost. A boolean holds only true or false, and a String variable holds a reference to a String object or null.
The compiler enforces both rules. Incompatible assignments produce errors such as incompatible types or possible lossy conversion, and reading a variable that might not have a value produces variable might not have been initialized. Both errors are easy to avoid by initializing every variable when you declare it, with a value of the right type.
| Assigning a value of type | To a variable of type | Allowed? |
|---|---|---|
| int | int | Yes |
| int | double | Yes: the value is widened (5 becomes 5.0) |
| double | int | No, not without an explicit cast |
| boolean | int or double | No |
| String or null | String | Yes |
| int | String | No (but "" + 5 produces a String) |
Which Assignments Compile?
Decide which statements compile.
double weight = 60;
String label = null;
System.out.println(weight + " " + label);
60.0 null
int count = 2.0;
boolean done;
boolean copy = done;
- 1
double weight = 60;compiles: anintvalue widens to adouble. - 2
String label = null;compiles: a reference variable may holdnull, and printing it shows the word null. - 3
int count = 2.0;fails: adoublevalue is not compatible with anintvariable without a cast. - 4
boolean copy = done;fails:donewas declared but never assigned, and every variable must have a value before it is used.
The variable that changes is always on the left. total = price; copies price into total; price = total; does the opposite. When an assignment seems to have no effect, check whether its two sides were reversed.
6Reference Variables, Objects, and null
Assignment works the same way for reference variables, but what gets stored is a reference to an object rather than the object itself. A reference variable can be assigned a newly created object, a reference copied from another variable, or the special literal null. The literal null indicates that a reference is not associated with any object.
A null reference is useful as a placeholder meaning "no object yet," but it cannot be used to call methods: calling a method on a null reference throws a NullPointerException. When a reference variable might be null, the program must make sure it refers to an object before using it.
null. With null, the variable exists but there is no object to use.String s = null; and String s = ""; are different. The empty string is a real object with length 0; null means there is no object. Printing null shows the word null, but calling s.length() when s is null stops the program with an exception.
Four Habits for Assignment Statements
1. Read = as "Becomes"
The left side changes; the right side is only read.
2. Evaluate Right, Store Left
The whole right side uses the current values before anything changes.
3. Trace in Order
One row per statement, one column per variable; copy unchanged values down.
4. Type the Right Side First
The expression's type is fixed before it reaches the variable.
Every variable must be assigned a value before it can be used in an expression, and that value must be from a compatible data type; a variable is initialized the first time it is assigned a value. Reference types can be assigned a new object or null, a special value indicating that a reference is not associated with any object. The assignment operator = allows a program to initialize or change the value stored in a variable: the value of the expression on the right is stored in the variable on the left. During execution, an expression is evaluated to produce a single value whose type is based on the evaluation of the expression.