Chapter 11. Core Utilities
In this chapter, we’ll continue our look at the core Java APIs, covering more of the
tools of the java.util
package. The java.util
package includes a wide range of utilities
including tools for mathematical operations, working with dates and times, holding
structured collections of objects, storing user preference data, and logging.
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.
Java provides the java.util.Random
class for
generating random numbers.
First, a few words about built-in arithmetic in Java. 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 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 |
Get Learning Java, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.