Java Reference
In-Depth Information
-
Similarly, for the
||
connector, in
Expr1 || Expr2
do not evaluate
Expr2
if
Expr1
is evaluated to
true
since we already know that in that case
Expr1
|| Expr2 = true
whatever the
true/false
value of expression
Expr2
.
The lazy evaluation of boolean predicates will become helpful when manipu-
lating arrays later on. For now, let us illustrate these notions with a simple
example:
Program 2.2
Lazy evaluation of boolean predicates
class
LazyEvaluation
{
public static void
main ( String [ ]
args )
{
double
x=3.14, y=0.0;
boolean
test1 , test2 ;
// Here division by zero yields a problem
// But this is prevented in the && by first checking
whether the denominator is
// zero or not
if
((y!=0.0) && (x/y
>
2.0))
{
// Do nothing
;
}
else
{
// Block
test1=(y!=0.0) ;
test2=(x/y
>
2.0) ;
System . out . println (
"Test1:"
+test1+
" Test2:"
+test2 ) ;
System . out . println (
"We did not evaluate x/y that is
equal to "
+(x/y ) ) ;
}
// Here, again we do not compute x/y since the first term
is true
if
(( y==0.0)
||
(x/y
>
2.0))
{
// Block
System . out . println (
"Actually, again, we did not
evaluate x/y that is equal to "
+(x/y ) ) ;
}
}
}
Running this program, we get the following console output:
Test1:false Test2:true
We did not evaluate x/y that is equal to Infinity
Actually, again, we did not evaluate x/y that is equal to Infinity
Search WWH ::
Custom Search