Do this...
Create a test-case class named
Experiment12Test
.
There are some assignment operations that are performed so often that Java provides special operators for them. For example, instead of writing
sum = sum + count;
Java provides the +=
operator that allows us to
write the same with fewer characters:
sum += count;
Similarly, to double the value in result
, we can
write this:
result *= 2;
Such shortcut operators save us from having to retype the same identifiers twice, and Java provides such a shortcut for each of the arithmetic operators.
Each of these shortcut operators can be chained in the same manner as a normal assignment. The shortcut assignment operators are also right associative.
Do this...
Create a test method in Experiment12Test
named
testAssignmentShortcuts()
, and add this code to the
method:
int w = 8, x = 4, y = 2, z = 1; w -= x /= y *= z += 1; assertEquals("value of w", ???, w); assertEquals("value of x", ???, x); assertEquals("value of y", ???, y); assertEquals("value of z", ???, z);
Replace the ???s with appropriate values, compile, and run for a green bar.
As confusing as that multi-shortcut-assignment statement is, you should be relieved that statements like this are practically never used. One shortcut-assignment operator per statement is plenty enough and are used quite often.