How to Use Java Packages and Import Declarations - dummies

How to Use Java Packages and Import Declarations

By Barry Burd

In Java, you can group a bunch of classes into something called a package. In fact, the classes in Java’s standard API are divided into about 200 packages. Here, you can check out the packages named java.util, java.lang, and java.io.

The class java.util.Scanner

The package java.util contains about 50 classes, including the very useful Scanner class. Like most other classes, this Scanner class has two names — a fully qualified name and an abbreviated simple name. The class’s fully qualified name is java.util.Scanner, and the class’s simple name is Scanner.

You get the fully qualified name by adding the package name to the class’s simple name. (That is, you add the package name java.util to the simple name Scanner. You get java.util.Scanner.)

An import declaration lets you abbreviate a class’s name. With the declaration

import java.util.Scanner;

the Java compiler figures out where to look for the Scanner class. So instead of writing java.util.Scanner throughout your code, you can just write Scanner.

The class java.lang.System

The package java.lang contains about 35 classes, including the ever-popular System class. (The class’s fully qualified name is java.lang.System, and the class’s simple name is System.) Instead of writing java.lang.System throughout your code, you can just write System. You don’t even need an import declaration.

Among all of Java’s packages, the java.lang package is special. With or without an import declaration, the compiler imports everything in the java.lang package. You can start your program with import java.lang.System. But if you don’t, the compiler adds this declaration automatically.

The static System.out variable

What kind of importing must you do in order to abbreviate System.out.println? How can you shorten it to out.println? An import declaration lets you abbreviate a class’s name. But in the expression System.out, the word out isn’t a class. The word out is a static variable. (The out variable refers to the place where a Java program sends text output.) So you can’t write

//This code is bogus. Don't use it:
import java.lang.System.out;

What do you do instead? You write

import static java.lang.System.out;