Professional Documents
Culture Documents
2.8. The Assignment Operator
2.8. The Assignment Operator
var = expression;
int x, y, z;
x = y = z = 100;
This works because the assignment operator yields the value of the right-hand expression.
Thus, the value of z = 100 is 100, which is then assigned to y, and this in turn is assigned to
x.
Using a chain of assignment is an easy way to set a group of variables to a common value.
Shorthand Assignments
Java provides special shorthand assignment operators that simplify the coding of certain
assignment statements. Let's begin with an example. The assignment statement
x = x + 10;
can be written as
x += 10;
The operator pair += tells the compiler to assign to x the value of x plus 10.
Here's another example of shorthand assignment. The statement
x = x - 100;
is the same as
x -= 100;
var op = expression;
The compound assignment operators provide two benefits — they're more compact than
their "longhand" equivalents and they're implemented more efficiently by the Java run-
time system. You'll often see compound assignment operators in professionally-written
Java programs.
Summary
In this lesson, you learned about the assignment operator (=), which may be the simplest
and most common operator you'll use in Java programs.
You also learned that you can set up chains of assignment, such as x = y = z = 100, in which
each variable in turn (working from right to left) is assigned the value 100.
Finally, you learned about the shorthand assignment operators, also known as compound
assignment operators. They let you write expressions such as x = x + 10 in the simpler form
x += 10.