As you saw in Chapter 3, the assignment operator causes the operand on the left side of the operator to have its value changed to whatever is on the right side of the operator. The following expression assigns the value 15 to myVariable
:
myVariable = 15;
The operand on the right doesn’t have to be a constant; it can be another variable. For example, if myVariable
is set to 15, you can then write this:
myOtherVariable = myVariable;
This means that myOtherVariable
is now equal to the value in myVariable
, which is 15. Remember that in assignment, it’s the variable on the left that gets the assigned value.
The assignment operator also allows you to chain assignments, assigning the same value to multiple variables, as follows:
myOtherVariable = myVariable = 15;
The preceding statement assigns 15 to myVariable
, and then also assigns the value (15) to myOtherVariable
. This works because the statement:
myVariable = 15;
is an expression; it evaluates to the value assigned. That is, the expression:
myVariable = 15;
itself evaluates to 15, and it is this value (15) that is then assigned to myOtherVariable
.