Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time
exception when denom is zero. If this line of code were written using the single & version
of AND, both sides would be evaluated, causing a run-time exception when denom is zero.
It is standard practice to use the short-circuit forms of AND and OR in cases involving
Boolean logic, leaving the single-character versions exclusively for bitwise operations. However,
there are exceptions to this rule. For example, consider the following statement:
if(c==1 & e++ < 100) d = 100;
Here, using a single & ensures that the increment operation will be applied to e whether c
is equal to 1 or not.
The Assignment Operator
You have been using the assignment operator since Chapter 2. Now it is time to take a formal
look at it. The assignment operator is the single equal sign, =. The assignment 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:
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
This fragment sets the variables x, y, and z to 100 using a single statement. This works
because 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.
The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else
statements. This operator is the ?. It can seem somewhat confusing at first, but the ? can be
used very effectively once mastered. The ? has this general form:
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is
true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ?
operation is that of the expression evaluated. Both expression2 and expression3 are required
to return the same type, which can't be void.
Here is an example of the way that the ? is employed:
ratio = denom == 0 ? 0 : num / denom;
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks