|
A very common practice is to perform an operation on the value of a variable and then store the result back in the variable. For example, you might want to do the following:
x = x - y;
For situations like this, Java provides an abbreviation called compound assignment. A compound assignment lets you modify a variable (in certain restricted ways) and store the value back in the variable, all in a single statement. Compound assignments have the form variable op= expression;, where op is a binary operation symbol that is immediately followed by =.
Table 3.3 summarizes the compound assignment operators. (The table assumes that b is boolean and x is of some numeric type.)
Operator | Example | Equivalent |
---|---|---|
+= | x += 5; | x = x+5; |
-= | x -= 5; | x = x-5; |
*= | x *= 5; | x = x*5; |
/= | x /= 5; | x = x/5; |
%= | x %= 5; | x = x%5; |
<<= | x <<= 5; | x = x<<5; |
>>= | x >>= 5; | x = x>>5; |
>>>= | x >>>=5; | x = x>>>5; |
&= | b &= false; | b = b&false; |
|= | b |= false; | b = b|false |
^= | b ^= false; | b = b^false; |
Compound assignments provide no new functionality. They just provide a convenient way to abbreviate.
|