Java Reference
In-Depth Information
<
less than
<=
less than or equal to
>
greater than
>=
greater than or equal to
==
equal to
!=
not equal to
One of the most frequent programming errors is to use the equality symbol
=
instead of the relational operator
==
to test for equalities:
int x=0;
if (x=1) System.out.println("x equals 1");
else System.out.println("x is different from 1");
Fortunately, the compiler generates an error message since in that case types
boolean/int
are incompatible when performing type checking in the expression
x=1
. But beware that this will not be detected by the compiler in the case of
boolean variables:
boolean x=false;
if (x=true) System.out.println("x is true");
else System.out.println("x is false");
In that case the predicate
x=true
contains an assignment
x=true
and the
evaluated value of the “expression” yields
true
, so that the program branches
on the instruction
System.out.println("x is true");
.
A boolean predicate may consist of several relation operators connected using
logical operators
from the table:
&&
and
||
or
!
not
The logic truth tables of these connectors are given as:
||
&& true false
true true false
false false false
true false
true true true
false true false
Whenever logical operators are used in predicates, the boolean expressions are
evaluated in a lazy fashion as follows:
-
For the
&&
connector, in
Expr1 && Expr2
do not evaluate
Expr2
if
Expr1
is evaluated to
false
since we alreaady know that in that case that
Expr1
&& Expr2 = false
whatever the
true/false
outcome value of expression
Expr2
.
Search WWH ::
Custom Search