Logical And
Certain additional comments are necessary when talking Java
rather than some abstract mathematics. For instance, there
is an identity relating two programs:
Consider the program:
Logical Or
The logical-or can also be interpreted more closely:
if ( a && b ) { S ; }
is the same as
if ( a )
if ( b ) { S ; }
where S
represents any statement.
This means that certain nested if's are equivalent to
bringing together the conditional clauses by &&
.
In terms of pure mathematics, logical-and is commutative:
a AND b = b AND a // pure mathematics
however a && b
is not the same as
b && a
in many programming languages,
including Java.
if ( (i>0) && (f(i) ) { S ; }
where f
is a function taking positive integers
and returning boolean. By interpreting this as:
if ( i>0 )
if ( f(i) ) { S ; }
we see that f
is never even called if i
is out of its proper range. In general, for a complex logical-and
such as:
( a && b && ... && z )
Java evaluates the
expressions a, b, ... , z
from left to right until
some expression yeilds false.
Since one false expression forces the complete logical-and to
evaluate false, there is no reason to continue.
This means that in certain instances, the order of the expressions
is important, in contrast to the mathematical commutivity of logical-and.
Here is an other example:
if ( (x!=0.0) && (1.0/x) > 2.0 ) { S ; }
Reverse the order of the expressions in the logical-or and
sometimes, when x==0.0
, you will have a run-time
error in the expression 1.0/x
.
if ( a || b ) { S ; }
is the same as:
if ( a ) { S ; }
else if ( b ) { S ; }
Java evaluates the components of the logical-or, a
then b
and so on, until one yeilds true.
That is, for a complex logical-or:
( a || b || ... || z )
Java evaluates the expressions a, b, ... , z
from left
to right until some expression yeilds true.
Since one true result causes the entire logical-or to evaluate true,
there is no reason to continue evaluation.
Once again, while logical-or is commutative in pure mathematics,
in many programming languages, including Java, the order of
the expressions is important. Here is an example:
if ( (x==0) || ( 1.0/x > 2.0 ) ) { S ; }
Reverse the order of the expressions in the logical-or and
sometimes, when x==0.0
, you will have a run-time
error in the expression 1.0/x
.