Thursday, July 17, 2008

Stars in import Statements

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

These are some representative import statments. Each one has an asterisk (or "star") at the end of it. What does that mean?

The asterisk is a special pattern-matching character. It matches any combination of characters (letters, numbers, or special characters.) In other words, it will match any name of any class in the package. Let's say we want to import Frame, Panel, Component, Color, Dialog, Dimension, Graphics and Image from the java.awt package for a program we're writing. We could have the following import statements:
import java.awt.Frame;
import java.awt.Panel;
import java.awt.Component;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;

Since star can take the place of any name, we can replace all of those import statements with one:
import java.awt.*;

This imports every class in java.awt. It also imports all the interfaces, exceptions, and errors defined in java.awt. It makes absolutely everything in the java.awt package available to our program.

OK, then why do we need to do this?
import java.awt.*;
import java.awt.event.*;

If the * makes us get everything in java.awt, why do we need to then go an import java.awt.event.*?

The reason is that java.awt.event is a different package than java.awt. The stuff in java.awt.event isn't actually in java.awt. With package names, the dot notation is just a way of letting us know that the stuff in java.awt.event is related to the stuff in java.awt, and that we'll probably want to use the stuff in these packages together. But java.awt.event isn't in java.awt, the way that System.out is in the class System.

Just remember, every package with its own name is a totally different package. You can tell a class name from a package name by whether it is capitalized:
import java.awt.Color;

Color is a class in the java.awt package. This is one of the reasons we follow the convention of using a capital letter at the start of a class's name. Whereas this:
import java.awt.color.*;

is an import of the classes in the java.awt.color package. These classes are not in java.awt, so you can't import them using "import java.awt.*;"

The asterisk is a "regular expression" character. It and a number of other characters are a way of building up what are called regular expressions, which are a way of matching things without using the precise name. The asterisk is a "wildcard," it can stand for any character, or any number of any characters.