Math Utilities
Java supports integer and floating-point arithmetic directly in the
language. Higher-level math operations are supported through the
java.lang.Math class. As
you may have seen by now, wrapper classes for primitive data types allow
you to treat them as objects. Wrapper classes also hold some methods for
basic conversions.
First, a few words about built-in arithmetic in Java. Java handles
errors in integer arithmetic by throwing an ArithmeticException:
intzero=0;try{inti=72/zero;}catch(ArithmeticExceptione){// division by zero}
To generate the error in this example, we created the intermediate
variable zero. The compiler is somewhat
crafty and would have caught us if we had blatantly tried to perform
division by a literal zero.
Floating-point arithmetic expressions, on the other hand, don’t throw exceptions. Instead, they take on the special out-of-range values shown in Table 11-1.
Table 11-1. Special floating-point values
Value | Mathematical representation |
|---|---|
| 1.0/0.0 |
| -1.0/0.0 |
| 0.0/0.0 |
The following example generates an infinite result:
doublezero=0.0;doubled=1.0/zero;if(d==Double.POSITIVE_INFINITY)System.out.println("Division by zero");
The special value NaN (not a
number) indicates the result of dividing zero by zero. This value has the
special mathematical distinction of not being equal to itself (NaN != NaN evaluates to true). Use Float.isNaN() or Double.isNaN() to test for NaN.