Java Reference
In-Depth Information
This operator is also called the
question/colon operator
because of its
form, and the
ternary operator
because it is the only ternary (three-op-
erand) operator in the language.
9.2.7. Assignment Operators
The assignment operator
=
assigns the value of its right-operand expres-
sion to its left operand, which must be a variable (either a variable name
or an array element). The type of the expression must be assignment
compatible with the type of the variablean explicit cast may be needed-
see
Section 9.4
on page
216
.
An assignment operation is itself an expression and evaluates to the
value being assigned. For example, given an
intz
, the assignment
z = 3;
has the value 3. This value can be assigned to another variable, which
also evaluates to 3 and so that can be assigned to another variable and
so forth. Hence, assignments can be chained together to give a set of
variables the same value:
x = y = z = 3;
This also means that assignment can be performed as a side effect of
evaluating another expressionthough utilizing side effects in expressions
is often considered poor style. An acceptable, and common, example of
this is to assign and test a value within a loop expression. For example:
while ((v = stream.next()) != null)
processValue(v);