Packages: Import Statement Tutorial

I demonstrated in my Packages Part 1 Tutorial that we could access a class from another package using its fully qualified name. However, it would get really old really fast if we had to type in the fully qualified name every time we used a class or its members from another package. The import statement comes to rescue! The import statement must reside after the package statement and before the class declaration. You can use the import statement in a couple of different ways. The structure for the statement looks like this:
(import) (package.ClassName) (;)
(import) (package.*) (;) // wildcard * imports all available classes

This Packages tutorial mini-series will use packages and classes from previous package tutorials. You will need to keep those packages and classes around to complete the examples in this mini-series. I will modify the Hello class in the aboutme package to use an import statement and remove the fully qualified location class name syntax.

Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>cd aboutme

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.

package aboutme;

import location.MyLocation;
//import location.*;

class Hello {
    public static void main(String args[]) {
        String name = "Dan";
        System.out.println("Hello everybody, my name is " + name);
        MyLocation reside = new MyLocation();	
        System.out.println("I live in " + reside.whereILive()); 

Now switch back to the command prompt (CMD) and type in cd .. and press Enter.
Now type in javac aboutme\ and press Enter.
Now type in java aboutme.Hello and press Enter.

C:\Java\aboutme>cd ..
C:\Java\javac aboutme\
C:\Java\java aboutme.Hello
Hello everybody, my name is Dan
I live in Orlando, Orange County, Florida, United States

Final thoughts

The import statement will save you a ton of typing.