Compound Assignment


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.)

Table 3.3: Compound Assignment

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.




Ground-Up Java
Ground-Up Java
ISBN: 0782141900
EAN: 2147483647
Year: 2005
Pages: 157
Authors: Philip Heller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net