Java Reference
In-Depth Information
operating system. If you can find out how to set the PATH variable on your operating
system, you will know enough about these topics to understand this section.
Packages and
import
Statements
A
package
is Java's way of forming a library of classes. You can make a package from a
group of classes and then use the package of classes in any other class or program you
write without the need to move the classes to the directory (folder) in which you are
working. All you need to do is include an
import
statement
that names the package.
We have already used
import
statements with some predefined standard Java packages.
For example, the following, which we have used before, makes available the class
Scanner
of the package
java.util
:
package
import
statement
import
java.util.Scanner;
You can make all the classes in the package available by using the following instead:
Import
java.util.*;
There is no overhead cost for importing the entire package as opposed to just a few classes.
The
import
statements should be at the beginning of the file. Only blank lines,
comments, and
package
statements may precede the list of
import
statements. We
discuss
package
statements next.
import
Statement
You can use a class from a package in any program or class definition by placing an
import
statement
that names the package and the class from the package at the start of the file
containing the program (or class definition). The program (or class definition) need not be in
the same directory as the classes in the package.
SYNTAX
import
Package_Name.Class;
EXAMPLE
import
java.util.Scanner;
You can import all the classes in a package by using an asterisk in place of the class's name.
SYNTAX
import
Package_Name.*;
EXAMPLE
import
java.util.*;