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.
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.
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:
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:
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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!
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.
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.
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.
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.
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.
(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) 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.
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.