In a previous section, we mentioned using the assignment operator to assign initial values to variables and constants. Now let’s look at the assignment operator in more detail. The syntax for the assignment operator is:
target = expression;
An expression consists of operators and operands that evaluate to a single value. The value of the expression is then assigned to target (target gets expression), which must be a variable or a constant having a data type compatible with the value of the expression. If target is a variable, the value of the expression replaces any previous value the variable was holding. For example, let’s look at these instructions:
The first instruction declares an int named numberOfPlayers. This allocates four bytes in memory to a variable named numberOfPlayers and stores the value 10 in that variable. Then, the second statement changes the value stored in the variable numberOfPlayers to 10. The previous value of 11 is discarded.
An expression can be a single variable name or a literal of any type. The value of the expression is simply the value of the variable or the literal. For example, in these statements,
the literal 19 is an expression. Its value is 19, which is assigned to the variable ageOfConsummation. Then, in the second statement ageOfConsummation is an expression whose value is 19. Thus, the value 19 is mysteriously assigned to vahid (which is a special number that represents a unit in the Baha’i faith).
So after these statements have been executed, both ageOfConsummation and the unrelated(?) vahid will have the value 19.
One restriction, however, is that an assignment expression cannot include another variable unless that variable has been defined previously. The statement defining the bornProbability variable that follows is invalid, because it refers to complexConjugate, which is not defined until the next line.
The IDE notices the error and underlines the complexConjugate’s red.
If you scroll over it on Eclipse, you get the message:
complexConjugate cannot be resolved to a variable
Note that this is not because I multiplied complexConjugate by itself. It is because complexConjugate was not defined yet. The definition happened in the line below, and this matters.
[It should be noted that complex conjugates representing probability amplitude are vectors in Hilbert Space and representing them as mere integers on the real number line would defeat their purpose.]
An expression can be quite… complex. These may consist of multiple variables, constants, literals, and operators. Before we can look at examples of more complex expressions, however, we need to discuss the arithmetic operators in the next post.