Java Reference
In-Depth Information
resulting in false positives. This can be accomplished, for example, by choosing large but distinct
long
values for
x
and
z
, and a
double
value that is close to both
long
values for
y
. The following
program does exactly that. It prints
TRue true false
, clearly demonstrating the nontransitivity of
the
==
operator over primitives:
public class Transitive {
public static void main(String[] args) throws Exception {
long
x = Long.MAX_VALUE;
double
y = (double) Long.MAX_VALUE;
long
z = Long.MAX_VALUE - 1;
System.out.print ((x == y) + " "); // Imprecise!
System.out.print ((y == z) + " "); // Imprecise!
System.out.println(x == z); // Precise
}
}
The lesson is:
Beware of lossy widening primitive conversions to float and double.
They are
silent but deadly. They can violate your intuition and cause subtle bugs (
Puzzle 34
). More generally,
beware of mixed-type operations (
Puzzles 5
,
8
,
24
, and
31
). The lesson for language designers is the
same as for
Puzzle 34
: Silent loss of precision confuses programmers.
< Day Day Up >
Search WWH ::
Custom Search