THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
Cloneable would be the type of the expression; if one expression was int while the other was
String, then Object would be the resulting type.

Note that if either expression has a type of void (possible if the expression invokes a method with the void
return type) then a compile-time error occurs.


This operator is also called the question/colon operator because of its form, and the ternary operator because it
is the only ternary (three-operand) operator in the language.


9.2.7. Assignment Operators


The assignment operator = assigns the value of its right-operand expression 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 neededsee 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);


Here the next value is read from a stream and stored in the variable v. Provided the value read was not null,
it is processed and the next value read. Note that as assignment has a lower precedence than the inequality test
(see "Operator Precedence and Associativity" on page 221), you have to place the assignment expression
within parentheses.


The simple = is the most basic form of assignment operator. There are many other assignment forms. Any
binary arithmetic, logical, or bit manipulation operator can be concatenated with = to form another assignment
operatora compound assignment operator. For example,


arr[where()] += 12;


is the same as


arr[where()] = arr[where()] + 12;

Free download pdf