Java Reference
In-Depth Information
However, because the payment is stored in a variable of type
double
, such a state-
ment would print all the digits of the number. For example, for the log listed above, it
would print the following:
payment = $1783.6447655625927
That is a rather strange-looking output for someone who is used to dollars and
cents. For the purposes of this simple program, it's easy to cast the
double
to an
int
and report just the dollar amount of the payment:
System.out.println("payment = $" + (int) payment);
Most people trying to figure out their mortgage payments aren't that interested in
the pennies, so the program is still useful. In the next section, we will see how to
round a
double
to two decimal places.
There is something new at the beginning of this class file called an
import declara-
tion.
Remember that Java has a large number of classes included in what are collec-
tively known as the Java class libraries. To help manage these classes, Java provides
an organizational unit known as a
package.
Related classes are combined together
into a single package. For example, the
Scanner
class is stored in a package known
as
java.util
. Java programs don't normally have access to a package unless they
include an import declaration.
Package
A collection of related Java classes.
Import Declaration
A request to access a specific Java package.
We haven't needed an
import
declaration yet because Java automatically imports
every class stored in a package called
java.lang
. The
java.lang
package includes
basic classes that most Java programs are likely to use (e.g.,
System
,
String
,
Math
).
Because Java does not automatically import
java.util
, you have to do it yourself.
Java allows you to use an asterisk to import all classes from a package:
import java.util.*;
But some people prefer to specifically mention each class they import. The import
declaration allows you to import just a single class from a package, as in
import java.util.Scanner;
The problem is that once you start importing one class from a package, you're
likely to want to import others as well. We will use the asterisk version of
import
in
this topic to keep things simple.
Search WWH ::
Custom Search