AP Computer Science A · Study guide

Assignment Statements

AP® Computer Science A · Using Objects and Methods

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.

Big Picture

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.

Figure 1. The = 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 formWhat happensExample
type name = expression;Declares the variable and initializes itint laps = 4;
name = expression;Evaluates the expression and replaces the stored valuelaps = laps + 1;
ref = new ClassName(...);Stores a reference to a newly created objecttitle = new String("Hi");
ref = null;The reference variable refers to no objecttitle = 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.

Figure 2. An assignment evaluates the expression on the right using the values stored right now, then stores the single resulting value in the variable on the left.
Worked Example 1 Self-reference

Updating a Running Total

A savings tracker starts at 50 and adds three deposits. Predict the final balance.

Code
int balance = 50;
balance = balance + 20;
balance = balance + 35;
balance = balance - 10;
System.out.println("Balance: " + balance);
Output
Balance: 95
  1. 1Read each line as "becomes." balance becomes 50 + 20 = 70, then 70 + 35 = 105, then 105 − 10 = 95.
  2. 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.
Result: The final balance is 95. A variable can appear on both sides of an assignment because the right side is evaluated first.
Statementbalance
int balance = 50;50
balance = balance + 20;70
balance = balance + 35;105
balance = balance - 10;95
Common Mistake 1 · Reading = as "Equals"

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.

Figure 3. A trace table records every variable after each statement. Only the variable on the left of an assignment changes; all the others keep their values.
Worked Example 2 Tracing

A Trace Table for Four Assignments

Trace a, b, and c, then predict the output.

Code
int a = 4;
int b = a * 3;
a = b - a;
int c = a + b;
System.out.println(a + " " + b + " " + c);
Output
8 12 20
  1. 1int a = 4; a is 4.
  2. 2int b = a * 3; uses the current a (4): b is 12.
  3. 3a = b - a; uses the current values 12 and 4: a becomes 8. The old 4 is gone.
  4. 4int c = a + b; uses the new a (8) and b (12): c is 20.
Result: The output is 8 12 20, matching Figure 3. Each assignment reads the values stored at that moment.
Worked Example 3 Order of statements

When the Order of Assignments Matters

Two programs contain the same assignments in different orders. Predict both outputs.

Program A
int x = 2;
int y = 5;
x = x + y;
y = x * 2;
System.out.println(x + " " + y);
Output
7 14
Program B
int x = 2;
int y = 5;
y = x * 2;
x = x + y;
System.out.println(x + " " + y);
Output
6 4
  1. 1Program A. x becomes 2 + 5 = 7; then y becomes 7 × 2 = 14.
  2. 2Program B. y becomes 2 × 2 = 4 first; then x becomes 2 + 4 = 6.
  3. 3Why they differ. Each assignment uses whatever values exist when it runs, so changing the order changes which values are used.
Result: Program A prints 7 14 and Program B prints 6 4. Same statements, different order, different results.
Worked Example 4 Rotating values

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.

Code
int first = 10;
int second = 20;
int third = 30;
int saved = first;
first = second;
second = third;
third = saved;
System.out.println(first + " " + second + " " + third);
Output
20 30 10
  1. 1Save the value that will be overwritten first. first is replaced before its value is needed again, so copy it to saved.
  2. 2Shift the others. first = second; then second = third; move values along.
  3. 3Finish with the saved value. third = saved; places the original 10.
Result: The output is 20 30 10. Like a swap, a rotation needs one temporary variable to protect a value before it is overwritten.
Common Mistake 2 · Using a Value After It Has Been 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.

Worked Example 5 Expression types

The Value Has a Type Before It Is Stored

A program computes the average of 7 and 8. Predict what is stored and printed.

Code
int sum = 7 + 8;
double avg1 = sum / 2;
double avg2 = sum / 2.0;
System.out.println(avg1);
System.out.println(avg2);
Output
7.0
7.5
  1. 1sum / 2. Both operands are int, so the expression's value is the int 7. Only then is it stored in the double variable, becoming 7.0.
  2. 2sum / 2.0. One operand is a double, so the expression's value is 7.5, which is stored as is.
  3. 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.
Result: 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 typeTo a variable of typeAllowed?
intintYes
intdoubleYes: the value is widened (5 becomes 5.0)
doubleintNo, not without an explicit cast
booleanint or doubleNo
String or nullStringYes
intStringNo (but "" + 5 produces a String)
Worked Example 6 Compatibility

Which Assignments Compile?

Decide which statements compile.

Compiles
double weight = 60;
String label = null;
System.out.println(weight + " " + label);
Output
60.0 null
Does not compile
int count = 2.0;
Does not compile
boolean done;
boolean copy = done;
  1. 1double weight = 60; compiles: an int value widens to a double.
  2. 2String label = null; compiles: a reference variable may hold null, and printing it shows the word null.
  3. 3int count = 2.0; fails: a double value is not compatible with an int variable without a cast.
  4. 4boolean copy = done; fails: done was declared but never assigned, and every variable must have a value before it is used.
Result: Values must be compatible with the variable's type, and a variable must be initialized before its value is read.
Common Mistake 3 · Writing the Assignment Backward

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.

Figure 4. A reference variable can be assigned a new object or null. With null, the variable exists but there is no object to use.
Common Mistake 4 · Treating null as an Empty String

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.

Core Synthesis

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.