Java Reference
In-Depth Information
together are int values. When you multiply two int values, you get another int value. Java does
not have target typing , a language feature wherein the type of the variable in which a result is to be
stored influences the type of the computation.
It's easy to fix the program by using a long literal in place of an int as the first factor in each
product. This forces all subsequent computations in the expression to be done with long arithmetic.
Although it is necessary to do this only in the expression for MICROS_PER_DAY , it is good form to do
it in both products. Similarly, it isn't always necessary to use a long as the first value in a product,
but it is good form to do so. Beginning both computations with long values makes it clear that they
won't overflow. This program prints 1000 as expected:
public class LongDivision {
public static void main(String[] args) {
final long MICROS_PER_DAY = 24 L * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAY = 24 L * 60 * 60 * 1000;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}
}
The lesson is simple: When working with large numbers, watch out for overflow— it's a silent
killer. Just because a variable is large enough to hold a result doesn't mean that the computation
leading to the result is of the correct type. When in doubt, perform the entire computation using
long arithmetic.
The lesson for language designers is that it may be worth reducing the likelihood of silent overflow.
This could be done by providing support for arithmetic that does not overflow silently. Programs
could throw an exception instead of overflowing, as does Ada, or they could switch to a larger
internal representation automatically as required to avoid overflow, as does Lisp. Both of these
approaches may have performance penalties associated with them. Another way to reduce the
likelihood of silent overflow is to support target typing, but this adds significant complexity to the
type system [Modula-3 1.4.8].
< Day Day Up >
 
 
Search WWH ::




Custom Search