Assigning References
Copying reference values by assignment creates aliases. Below, the variable pizza1 is a reference to a pizza that is hot and spicy, and pizza2 is a reference to a pizza that is sweet and sour.
Pizza pizza1 = new Pizza(“Hot&Spicy”);
Pizza pizza2 = new Pizza(“Sweet&Sour”);
pizza2 = pizza1;
Assigning pizza1 to pizza2 means that pizza2 now refers to the same pizza as pizza1, the hot and spicy one. After the assignment, these variables are aliases and either one can be used to manipulate the hot and spicy Pizza object.
Assigning a reference value does not create a copy of the source object denoted by the reference variable on the right-hand side. It merely assigns the reference value of the variable on the right-hand side to the variable on the left-hand side so that they denote the same object. Reference assignment also does not copy the state of the source object to any object denoted by the reference variable on the left-hand side.
A more detailed discussion of reference assignment can be found in §5.8, p. 261.
Multiple Assignments
The assignment statement is an expression statement, which means that application of the binary assignment operator returns the value of the expression on the right-hand side.
int j, k;
j = 10; // (1) j gets the value 10, which is returned
k = j; // (2) k gets the value of j, which is 10, and this value is returned
The value returned by an assignment statement is usually discarded, as in the two assignment statements above. We can verify the value returned as follows:
System.out.println(j = 10); // j gets the value 10, which is printed.
System.out.println(k = j); // k gets the value of j, i.e. 10, which is printed
The two assignments (1) and (2) above can be written as multiple assignments, illustrating the right associativity of the assignment operator:
k = j = 10; // (k = (j = 10))
Multiple assignments are equally valid with references:
Pizza pizzaOne, pizzaTwo;
pizzaOne = pizzaTwo = new Pizza(“Supreme”); // Aliases
The following example shows the effect of operand evaluation order:
int[] a = {10, 20, 30, 40, 50}; // An array of int (
§3.9
,
p. 119
)
int index = 4;
a[index] = index = 2; // (1)
What is the value of index, and which array element a[index] is assigned a value in the multiple assignment statement at (1)? The evaluation proceeds as follows:
a[index] = index = 2;
a[4] = index = 2;
a[4] = (index = 2); // index gets the value 2. = is right associative.
a[4] = 2; // The value of a[4] is changed from 50 to 2.
The following declaration statement will not compile, as the variable v2 has not been declared:
int v1 = v2 = 2016; // Only v1 is declared. Compile-time error!