Skip to main content
Logo image

Section 2.4 Assignment statements

So far we’ve learned how to declare variables and also how to use them in arithmetic expressions to compute new values. And we’ve seen how to use System.out.print() and System.out.println() to output the results of those computations to make programs that do things that the human running the program can see.
That’s fine if the thing we want to compute is not too complicated. But if the computation we want to our program to perform is involved enough, it can be useful to break it down into smaller parts and save the results of intermediate expressions in their own variables. And sometimes it’s useful to update the value of an existing variable with a new value. That’s where assignment statements come in.
Relatedly, if we want to take input from the user, for instance using the Scanner class we discussed in SubsectionΒ 2.2.5Β Input, we’ll often assign the values we get from the user to variables that we then use in our computations.

Subsection 2.4.1 Simple assignments

Assignment statements are used both to initialize and change the value stored in a variable using the assignment operator which is written with a single equals sign: =. An assignment statement always consists of a single variable on the left hand side of the = and a single expression on the right hand side. The expression is evaluated and then the resulting value is stored in the variable, initializing it if this is the first time it has been assigned a value or replacing its old value with a new value.
When we read code out loud, we usually read an assignment statement like x = 10 as β€œx gets 10” or β€œset x to 10”.
To take a simple example of initializing and then reassigning a variable, suppose we are keeping track of the score in a game. We need to declare and initialize the variable with something like this:
int score = 0;
That is an assignment as part of the variable declaration. It initializes the variable score to the value 0. Then as the game progresses and the player scores points we need to update the value of score with a line like this:
score = score + 1;
This increments the variable, setting its value to its current value plus one. As a formula in math class it would look strange since nothing plus one is equal to itself. But it makes sense in coding because the = is an assignment operator. Java just evaluates the expression on the right, score + 1, which produces some number and then that number becomes the new value of the variable score.

Note 2.4.1.

Notice that in the second line, when we are assigning a new value to score, we do not specify its type again. We only need to declare a variable once. If we did write:
int score = score + 1;
it would be an error because this code would need to evaluate the right hand side of the assignment in order to get score’s initial value but that would require getting the value of score before it was initialized.

Activity 2.4.1. Incrementing score.

Try the code below to see how score is incremented by 1. Try substituting 2 instead of 1 to see what happens.

Subsection 2.4.2 Data types in assignments

Whenever we assign a value to a variable, the type of the value produced by the expression must be compatible with the declared type of the variable. Usually this means there are the same type, such as assigning an int value to an int variable or a double value to a double variable. But similar to the way we can use a mix of int and double values in an arithmetic expression and get a double result, we can also assign an int value to a double variable and it will be automatically converted to the equivalent double. In the next lesson, we will see how to explicitly convert values to different types.

Activity 2.4.2. Type mismatch.

The code below looks okay at first glance, but if you run it, you will see that there is an error of incompatible types. Change the data type of one of the variables to fix the error.

Activity 2.4.3. Variable assignments.

The following video by Dr. Colleen Lewis shows how variables can change values in memory using assignment statements.
As we saw in the video, we can set one variable’s value to a copy of the value of another variable like y = x;. This won’t change the value of the variable that you are copying from.
Let’s step through the following code in the Java visualizer to see the values in memory (click here if the code below does not generate). Click on the Next button at the bottom of the code to see how the values of the variables change. You can run the visualizer on any Active Code in this book by just clicking on the Code Lens button at the top of each Active Code.
Keep clicking on the Next button at the bottom of the code to see how the values of the variables change as you step through the running program.

Activity 2.4.4. Trace assignments.

What are the values of x, y, and z after the following code executes? You can step through this code by clicking on this Java visualizer link.
int x = 0;
int y = 1;
int z = 2;
x = y;
y = y * 2;
z = 3;
  • x = 0, y = 1, z = 2
  • These are the initial values in the variable, but the values are changed.
  • x = 1, y = 2, z = 3
  • x changes to y’s initial value, y’s value is doubled, and z is set to 3
  • x = 2, y = 2, z = 3
  • Remember that the equal sign doesn’t mean that the two sides are equal. It sets the value for the variable on the left to the value from evaluating the right side.
  • x = 0, y = 0, z = 3
  • Remember that the equal sign doesn’t mean that the two sides are equal. It sets the value for the variable on the left to the value from evaluating the right side.

Activity 2.4.5. Swap values.

The following has the correct code to β€˜swap’ the values in x and y (so that x ends up with y’s initial value and y ends up with x’s initial value), but the code is mixed up and contains one extra block which is not needed in a correct solution. Drag the needed blocks from the left into the correct order on the right. Check your solution by clicking on the Check button. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks. After three incorrect attempts you will be able to use the Help Me button to make the problem easier.

Subsection 2.4.3 Compound assignment operators

Compound assignment operators +=, -=, *=, /=, and %= are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x. It is the same as x = x + 1. This pattern is possible with any operator put in front of the = sign, as seen below.
If you need a way to remember the order of the two characters in the compound operators, think about the order things happen: first we use the math operator, such as +, to get the new value and then the value is assigned back to the variable with =. So it’s operator then equals sign: +=.
Since changing the value of a variable by one is especially common, there are two extra concise operators ++ and --, also called the plus-plus or increment operator and minus-minus or decrement operator that set a variable to one greater or less than its current value.
Thus x++ is even more concise way to write x = x + 1 than the compound operator x += 1. You’ll see this shortcut used a lot in loops when we get to them. Similarly, y-- is a more concise way to write y = y - 1. These shortcuts only exist for + and - as they don’t really make sense for other operators.

Note 2.4.2.

If you’ve heard of the programming language C++, the name is an inside joke that C, an earlier language which C++ is based on, had been incremented or improved to create C++.
Here’s a table of all the compound arithmetic operators and the extra concise increment and decrement operators and how they relate to fully written out assignment expressions. You can run the code below the table to see these shortcut operators in action!
Table 2.4.3. Arithmetic compound assignment operators
Operator + - * / %
Written out x = x + 1 x = x - 1 x = x * 2 x = x / 2 x = x % 2
Compound x += 1 x -= 1 x *= 2 x /= 2 x %= 2
Extra concise x++ x-- none none none

Note 2.4.4.

If you look at real-world Java code, you may occasionally see the ++ and -- operators used before the name of the variable, like ++x rather than x++. That is legal but not something that you will see on the AP exam.
If the operator is after the variable name (called the postfix operator), the value of the variable is changed after evaluating the variable to get its value. And if the operator is before the variable (the prefix operator), the value of the variable in incremented before the variable is evaluated to get the value of the expression. For example, if x is 10 and we write, System.out.println(x++) it will print 10 but afterwards x will be 11. On the other hand if we write, System.out.println(++x), it will print 11 and afterwards the value will be 11.
The AP exam will never use the prefix form of these operators nor will it use the postfix operators in a context where the value of the expression matters.

Activity 2.4.6.

Run the code below to see what the ++ and shortcut operators do. Click on the Show Code Lens button to trace through the code and the variable values change in the visualizer. Create more compound assignment statements with shortcut operators as described below and work with a partner to guess what they would print out before running the code.

Activity 2.4.7.

What are the values of x, y, and z after the following code executes?
int x = 0;
int y = 1;
int z = 2;
x--;
y++;
z+=y;
  • x = -1, y = 1, z = 4
  • This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y.
  • x = -1, y = 2, z = 3
  • This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y.
  • x = -1, y = 2, z = 2
  • This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y.
  • x = 0, y = 1, z = 2
  • This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y.
  • x = -1, y = 2, z = 4
  • This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y.

Activity 2.4.8.

What are the values of x, y, and z after the following code executes?
int x = 3;
int y = 5;
int z = 2;
x = z * 2;
y = y / 2;
z++;
  • x = 6, y = 2.5, z = 2
  • This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3).
  • x = 4, y = 2.5, z = 2
  • This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3).
  • x = 6, y = 2, z = 3
  • This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3).
  • x = 4, y = 2.5, z = 3
  • This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3).
  • x = 4, y = 2, z = 3
  • This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3).

Subsection 2.4.4 Code Tracing Challenge and Operators Maze

Use paper and pencil or the question response area below to trace through the following program to determine the values of the variables at the end.
Code Tracing is a technique used to simulate a dry run through the code or pseudo code line by line by hand as if you are the computer executing the code. Tracing can be used for debugging or proving that your program runs correctly or for figuring out what the code actually does.
Trace tables can be used to track the values of variables as they change throughout a program. To trace through code, write down a variable in each column or row in a table and keep track of its value throughout the program. Some trace tables also keep track of the output and the line number you are currently tracing.
Figure 2.4.5.
Figure 2.4.6.
Trace through the following code:
int x = 0;
int y = 5;
int z = 1;
x++;
y -= 3;
z = x + z;
x = y * z;
y %= 2;
z--;

Project 2.4.9.

Write your trace table for x, y, and z here showing their results after each line of code.
After doing this challenge, play the Operators Maze game. See if you and your partner can get the highest score!

Subsection 2.4.5 Coding Challenge: Dog Years

dog
In this coding challenge, you will calculate your age, and your pet’s age from your birth dates, and your pet’s age in dog years. In the code below, type in the current year, the year you were born, the year your dog or cat was born (if you don’t have one, make one up!) in the variables below. Then write formulas in assignment statements to calculate how old you are, how old your dog or cat is, and how old they are in dog years which is 7 times a human year. Finally, print it all out. If you are pair programming, switch drivers (who has control of the keyboard in pair programming) after every line of code.

Project 2.4.10. Dog Years.

Calculate your age and your pet’s age from the birth dates, and then your pet’s age in dog years.
Your teacher may suggest that you use a Java IDE with interactive input using the Scanner class for this challenge, for example this JuiceMind activity or repl template if you want to try the challenge with input.

Subsection 2.4.6 Summary

  • (AP 1.4.A.2) 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.
  • (AP 1.4.A.1) Every variable must be assigned a value before it can be used in an expression. That value must be from a compatible data type.
  • (AP 1.4.A.1) A variable is initialized the first time it is assigned a value.
  • (AP 1.4.A.1) Reference types can be assigned a new object or null if there is no object. The literal null is a special value used to indicate that a reference is not associated with any object.
  • (AP 1.4.A.3) During execution, an expression is evaluated to produce a single value. The value of an expression has a type based on the types of the values and operators used in the expression.
  • (AP 1.6.A.1) Compound assignment operators (+=, -=, *=, /=, %=) can be used in place of the assignment operator in numeric expressions. A compound assignment operator performs the indicated arithmetic operation between the current value of the variable on the left and the value on the right and then assigns the resulting value to the variable on the left.
  • (AP 1.6.A.2) The increment operator (++) and decrement operator (--) are used to add 1 or subtract 1 from the stored value of a numeric variable. The new value is assigned to the variable.

Subsection 2.4.7 AP Practice

Activity 2.4.11. Mental execution.

Consider the following code segment.
int a = 5;
int b = a / 2;
double c = a / 2.0;
double d = 5 + a / b * c - 2;
System.out.println(d);
What is printed when the code segment is executed?
  • Don’t forget that the result will be a double since at least one double value is involved.
  • Yes, d is computed as (5 + ((5 / 2) * 2.5) - 2) where 5 / 2 is computed using int division which gives us 2. So 5 + 5.0 - 2.
  • Don’t forget that division and multiplication will be done first due to operator precedence, and that an int divided by an int gives a truncated int result where everything to the right of the decimal point is dropped.
  • An incompatible type error will occur.
  • No error will occur since the double result is saved in a double.
You have attempted of activities on this page.