Java Reference
In-Depth Information
error. Finally, the normal AND operator is tried. This causes both operands to be evaluated,
which leads to a run-time error when the division by zero occurs.
One last point: The formal specification for Java refers to the short-circuit operators as
the
conditional-or
and the
conditional-and
operators, but the term “short-circuit” is com-
monly used.
The Assignment Operator
You have been using the assignment operator since
Chapter 1
. Now it is time to take a
formal look at it. The
assignment operator
is the single equal sign,
=
. This operator works
in Java much as it does in any other computer language. It has this general form:
var = expression;
Here, the type of
var
must be compatible with the type of
expression
.
The assignment operator does have one interesting attribute that you may not be familiar
with: it allows you to create a chain of assignments. For example, consider this fragment:
This fragment sets the variables
x
,
y
, and
z
to 100 using a single statement. This works be-
cause the
=
is an operator that yields the value of the right-hand expression. Thus, the value
of
z = 100
is 100, which is then assigned to
y
, which 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 shown here
can be written, using Java shorthand, as