Math Utilities
Java supports
integer and floating-point arithmetic
directly. Higher-level math operations are supported through the
java.lang.Math
class. Java provides wrapper classes for all primitive data types, so
you can treat them as objects if necessary. Java also provides the
java.util.Random
class for generating random numbers.
Java
handles errors in integer arithmetic by throwing an
ArithmeticException:
int zero = 0;
try {
int i = 72 / zero;
}
catch ( ArithmeticException e ) {
// 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 a 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 9.3.
Table 9-3. 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:
double zero = 0.0;
double d = 1.0/zero;
if ( d == Double.POSITIVE_INFINITY )
System.out.println( "Division by zero" );
The special value NaN
indicates the result is “not a number.” The value
NaN has the special distinction of not being equal
to itself (NaN != NaN evaluates to
true). Use Float.isNaN( ) or
Double.isNaN( ) to test for
NaN.
The java.lang.Math Class
The java.lang.Math class provides Java’s math library. All ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access