Importing Libraries in Java

Java classes and interfaces can be organized into packages to group related types and for name-space management.

Java comes with a rich set of pre-written classes that a programmer can use while developing Java programs. These classes are organized into packages. The following are just a few of the large number of different packages in Java at Oracle’s Java API Specifications:

  • java.applet: The "applet" package provides the classes necessary to create an applet and the classes an applet uses to communicate with its applet context.
  • java.awt: The "awt" package contains all of the classes for creating user interfaces and for painting graphics and images.
  • java.lang: The "lang" package provides classes that are fundamental to the design of the Java programming language.

In order to use a Java class declared in these packages, you need to include an import statement before class declaration in your program. The import statement starts with the keyword import, followed by the name of the java package.

Types of Imports

There are two kinds of import statements.

1) Specific import: This statement imports only a single class into the program. For example, to import the JOptionPane class from the javax.swing package, we can use the following import statement:

import javax.swing.JOptionPane;

The above statement will import only one class: the JOptionPane class.

2) Wild card import: The wild card import statement imports all the classes in a package.

import javax.swing.*;

This statement imports all the classes from the javax.swing package into your program.


Using Imports

Unless there are comments, the first statement in a Java file should be a package declaration. Following this package declaration, you can add the import statements as listed above.

These import statements allow you to use classes from other packages. You can then continue on to define your classes in the file that may use classes from imported packages.

So a source file called in the geometry directory may look like this:

package geometry;
import java.awt.*;
pubic class rectangle {


Key Points about Imports

Following are some of the key points about importing libraries in Java.

  1. The import only tells the compiler where to look for the symbols and, as a result, doesn’t make the program much larger.
  2. The wildcard “*” makes the classes in the associated package visible, but not any of the classes in the sub-packages.
  3. All classes in the java.lang package are automatically visible and do not require an import.
  4. The order of imports is not important and they can be grouped for readability


Source: Saylor Academy
Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 License.

Last modified: Wednesday, April 17, 2019, 6:46 PM