Java Reference
In-Depth Information
Similarly, in the second statement, the two operands of the operator
&&
are
(a == b)
and
(x >= 7)
. Now, if the operand
(a == b)
evaluates to
false
, then the entire expression
evaluates to
false
because
false
&&
true
is
false
and
false
&&
false
is
false
.
Short-circuit evaluation (of a logical expression): A process in which the computer
evaluates a logical expression from left to right and stops as soon as the value of the
expression is determined.
EXAMPLE 4-19
Consider the following expressions:
(age >= 21) || (x == 5)
//Line 1
(grade == 'A') && (x >= 7)
//Line 2
For the expression in Line 1, suppose that the value of
age
is
25
. Because
(25 >= 21)
is
true
and the logical operator used in the expression is
||
, the expression evaluates
to
true
. Because of short-circuit evaluation, the computer does not evaluate the expres-
sion
(x == 5)
. Similarly, for the expression in Line 2, suppose that the value of
grade
is
'B'
. Because
('A' == 'B')
is
false
and the logical operator used in the expression
is
&&
, the expression evaluates to
false
. The computer does not evaluate
(x >= 7)
.
In Java,
&
and
|
are also operators. You can use the operator
&
in place of the operator
&&
in a
logical expression. Similarly, you can use the operator
|
in place of the operator
||
in a
logical expression. However, there is no short-circuit evaluation of the logical expressions if
&
is used in place of
&&
or
|
is used in place of
||
. For example, suppose that
a
and
b
are
int
variables, and
a = 10
and
b = 18
. After the evaluation of the expression
(a > 10) &&
(b++ < 5)
, the value of
b
is still 18. This is because the expression
a > 10
evaluates to
false
,and
false
&&
false
is
false
as well as
false
&&
true
is
false
,sousing
short-circuit evaluation the expression
(a > 10) && (b++ < 5)
evaluates to
false
and the
expression
(b++ < 5)
does not get evaluated.
Comparison of floating-point numbers for equality may not behave as you would expect.
For example, consider the following program.
public class
FloatingPointNumbers
{
public static void
main(String[] args)
{
double
x = 1.0;
double
y = 3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0;
Search WWH ::
Custom Search