Hands on Testing Java: Lab #3

Experiment #11: Assignment Expressions

Do this...
Create a test-case class named Experiment11Test.

Making an Assignment

If the purpose of a variable is to vary its value, then what code changes its value? The assignment statement is the most common way:

assignment-statement pattern
variable = expression;
  • expression is any valid Java expression.
  • variable is an identifier that has already been declared as a variable, whose type matches that of expression.

The statement is valid only if the variable and expression have the same type (e.g., both are integers). The expression is evaluated first, and then that value is placed in the variable.

Assignment Expressions Return a Value

In Java, the assignment symbol = is an operator that evaluates to a value, just like + and / evaluate to values: 2+3 evaluates to 5 and 11/5 evaluates to 2.

But what does, say, i = 5 evaluate to?

Try it out:

Do this...
Create a test method in Experiment11Test named testAssignmentExpressions(), and add this code to this experiment's test method:

int i = 66;
assertEquals("i assigned", ???, i = 5);

Replace the ??? with the appropriate value. Then compile, and run for a green bar.

So what possible use could this be? To answer this, we'll have to consider the associativity of the assignment operator.

Assignment Associativity

Do this...
Add these statements to your test method:

int j = 123;
int k = 456;
int m = 789;
int n = 0;
i = j = k = m = n;
assertEquals ("value of i", ???, i);
assertEquals ("value of j", ???, j);
assertEquals ("value of k", ???, k);
assertEquals ("value of m", ???, m);
assertEquals ("value of n", ???, n);

Hold up on replacing the ???s.

The key to those ???s is the statement that's emphasized in the code above, the multi-assignment statement.

The assignment operator is straightforward: change the variable on the left and return the value of the expression. So that's not a problem.

Precedence doesn't play a role here. Only assignment operators are used in the multi-assignment statement. So precedence isn't an issue here.

So the issue here must be associativity. If the assignment operator were left associative:

((((i = j) = k) = m) = n);

Look what's on the left side of the assignment operator with n on the right! How can we assign the value of n to the result of an expression? Perhaps there's some way we could make sense of these parentheses, but it doesn't seem intuitive or simple.

Perhaps assignment is right associative:

(i = (j = (k = (m = n))));

That seems to look better. Now m is on the left of the assignment operator with n on the right. We can evaluate that expression fine. And since that assignment evaluates to a value (i.e., n), the assignment to k also makes sense. Similarly, the assignments to j and i fall into place. This seems (relatively) simple and intuitive.

Do this...
Now replace the ???s, compile, and run for a green bar.