Experiment 13: Assignment Shortcuts


There are some assignment operations that are performed so commonly, Java provides special operators for them. For example, instead of writing

   sum = sum + count;

Java provides the += operator that allows us to write an equivalent statement more succinctly:

   sum += count;

Similarly, to double the value in result, we can write

   result = result * 2;

or we can more succinctly write:

   result *= 2;

Such "shortcut" operators save us from having to retype the same identifiers (count and result) twice, and Java provides such a "shortcut" for each of the arithmetic operators. That is, if D is an arithmetic operator, then an expression of the form:

   Variable1 = Variable1 D Expression

can be written as

   Variable1 D= Expression

Each of these "shortcut" operators can be chained in the same manner as a normal assignment. As a pencil-and-paper exercise, determine the values of w, x, y, and z after the following statements execute:

   int w = 8,
       x = 4,
       y = 2,
       z = 1;

   w -= x /= y *= z += 1;

In what order are the operators applied?



What are the values of each variable following the assignment statement?



Using Express.java, verify the correctness of your prediction, and record any discrepancies in the space below.





You should now know how to use assignment "shortcuts" in order to avoid having to type the same variable's name more than once.


Back to the Exercise List

Forward to the Next Experiment


Back to the Table of Contents

Back to the Introduction


Copyright 2000 by Prentice Hall. All rights reserved.