Java Reference
In-Depth Information
More About Assignment
Assigning a value to a variable is an expression because it produces a value. Because of
this feature, you can string assignment statements together the following way:
x = y = z = 7;
In this statement, all three variables end up with the value of 7 .
The right side of an assignment expression always is calculated before the assignment takes
place. This makes it possible to use an expression statement as in the following code:
2
int x = 5;
x = x + 2;
In the expression x = x + 2 , the first thing that happens is that x + 2 is calculated. The
result of this calculation, 7, is then assigned to x .
Using an expression to change a variable's value is a common task in programming.
Several operators are used strictly in these cases.
Table 2.4 shows these assignment operators and the expressions they are functionally
equivalent to.
TABLE 2.4
Assignment Operators
Expression
Meaning
x = x + y
x += y
x = x - y
x -= y
x = x * y
x *= y
x = x / y
x /= y
CAUTION
These shorthand assignment operators are functionally equivalent
to the longer assignment statements for which they substitute. If
either side of your assignment statement is part of a complex
expression, however, there are cases where the operators are not
equivalent. For example, if x equals 20 and y equals 5 , the follow-
ing two statements do not produce the same value:
x = x / y + 5;
x /= y + 5;
When in doubt, simplify an expression by using multiple assign-
ment statements and don't use the shorthand operators.
 
Search WWH ::




Custom Search