Java Reference
In-Depth Information
Java has six relational operators:
Java
Math Notation
Description
>
>
Greater than
>=
>
Greater than or equal
<
<
Less than
<=
<
Less than or equal
==
=
Equal
!=
¬
Not equal
As you can see, only two relational operators (
>
and
<
) look as you would expect
from the mathematical notation. Computer keyboards do not have keys for
² ±
, or
¬
, but the
>=
,
<=
, and
!=
operators are easy to remember because they look
similar.
The
==
operator is initially confusing to most newcomers to Java. In Java, the
=
symbol already has a meaning, namely assignment. The
==
operator denotes
equality testing:
a = 5; //
Assign 5 to a
if (a == 5) . . . //
Test whether a equals 5
You will have to remember to use
==
for equality testing, and to use
=
for
assignment.
5.2.2 Comparing Floating-Point Numbers
You have to be careful when comparing floating-point numbers, in order to cope
with roundoff errors. For example, the following code multiplies the square root of
2 by itself and then subtracts 2.
double r = Math.sqrt(2);
double d = r * r - 2;
if (d == 0)
System.out.println("sqrt(2) squared minus 2 is
0");
else
System.out.println(
"sqrt(2) squared minus 2 is not 0 but
" + d);
188
189