Packages and Import Declarations in Java

By Barry Burd

Java has a feature that lets you lump classes into groups of classes. Each lump of classes is called a package. In the Java world, programmers customarily give these packages long, dot-filled names.

For instance, because someone’s registered the domain name, they might name a package com.allmycode.utils.textUtils. The Java API is actually a big collection of packages. The API has packages with names like java.lang, java.util, java.awt, javax.swing, and so on.

With this information about packages, you can clear up some of the confusion about import declarations. Any import declaration that doesn’t use the word static must start with the name of a package and must end with either of the following:

  • The name of a class within that package

  • An asterisk (indicating all classes within that package)

For example, the declaration

import java.util.Scanner;

is valid because java.util is the name of a package in the Java API, and Scanner is the name of a class in the java.util package. The dotted name java.util.Scanner is the fully qualified name of the Scanner class.

A class’s fully qualified name includes the name of the package in which the class is defined. (You can find out all this stuff about java.util and Scanner by reading Java’s API documentation.)

Here’s another example. The declaration

import javax.swing.*;

is valid because javax.swing is the name of a package in the Java API, and the asterisk refers to all classes in the javax.swing package. With this import declaration at the top of your Java code, you can use abbreviated names for classes in the javax.swing package — names like JFrame, JButton, JMenuBar, JCheckBox, and many others.

Here’s one more example. A line like

import javax.*;  //Bad!!

is not a valid import declaration. The Java API has no package with the one-word name javax. You may think that this line allows you to abbreviate all names beginning with javax (names like javax.swing.JFrame and javax.sound.midi), but that’s not the way the import declaration works. Because javax isn’t the name of a package, the line import javax.* just angers the Java compiler.