Java not only allows you to create packages, but it also provides the ability to import packages.
How to Import a Package in Java?
Importing a package into a file allows for the use of elements of that package. A package is imported at the beginning of a file. The import statement is used to import one or more classes.
Import a Specific Class
Below is the syntax to import a specific class from a package in Java.
import package1.package2.Classname;
When a class is imported, the members of that class become available. There are still restrictions on members with certain access modifiers.
Import All Classes
To import all classes in a package, the * operator is used.
import package1.package2.*;
The above statement imports all the classes inside of package2.
The Java Class Library
Many of the methods and tools you have been using to this point are available due to Java's Class Library. Java's Class Library is automatically imported for use in any class. Some of these packages include:
| Subpackage | Description |
|---|---|
| java.lang | Contains general-purpose classes |
| java.io | Contains I/O classes |
| java.net | Contains networking classes |
| java.applet | Contains applet classes |
Both the Math class and the System class belong in Java's Class Library.
As you progress into further Java development, you'll be importing many classes and packages into your Java classes. At times, you can have 20 to 30 import statements. Many of these imports will come from the Java class libraries, but most will come from 3rd party developers/organizations/projects.
You use dependency management and build tools named Maven and Gradle to manage these dependencies. This is something you will be covering in the next module of this series, "Java Developer Professional" program.
Summary: What is Java Import
- The
importstatement is used to import packages - Java packages in one file can be imported into another
- Either individual classes or everything from a package can be imported
- Java comes prebuilt with several packages already imported and ready for use in every file
Syntax
Here's the syntax for importing a package, where you can substitute the variables starting with your_ with your values.
// to import one class
import package1.package2.YOUR_CLASSNAME;
// to import everything in the package
import package1.package2.*;