Java packages
A package is a group of related classes and interfaces that work together to provide functionality for various purposes.
This lesson focuses on:
- Importing packages
- Different Java packages
Importing packages
The purpose of importing packages is to be able to use classes and interfaces located in those specific packages. If you try to use a class or interface without importing the package it is located in, you will get an error.
There is one package that is imported by default into all Java programs - the java.lang package. The java.lang package provides classes that are fundamental to developing Java programs. Classes within the java.lang package include the String class for working with text strings and the Math class for performing various calculations and working with numeric data, among others. For all other classes, you must import the appropriate package(s).
Importing packages is achieved by using the import keyword followed by a single space followed by the name of the package to be imported followed by the name of the class or interface to import followed by a semicolon.
NOTE: The import keyword should appear first in code, even before the class declaration!
Syntax:
import packageName.className; import packageName.interfaceName;
Example:
import java.util.Random;
import java.util.Vector;
class Book{
}
In the above example, a class named Book imports the Random and Vector classes from the java.util package. Because of this, the Book class can now use these classes from this package.
Instead of importing single classes or interfaces from packages, you can specify that a class imports all the classes and interfaces from a package using the * character.
Syntax:
import packageName.*;
Example:
import java.util.*;
class Book{
}
In the above example, a class named Book imports all the classes and interfaces from the java.util package using the * character. Because of this, the Book class can now use all the interfaces and classes located in the java.util package.
Different Java packages
Java provides many different packages for a wide variety of functionality.
Some of Java's packages:-
java.lang
This package provides classes that are fundamental to developing Java programs. This package is imported by default into Java programs.
-
java.io
This package provides classes for input and output.
-
java.awt
This package provides classes for creating graphical user interfaces, graphics, and images.
-
java.awt.font
This package provides classes for working with fonts.




