The ‘import’ Statement in Java



The import statement tells the compiler that which libraries you want to use. The Java import statement is similar to the C++ ‘#include’ directive. For example:

import java.lang.*;
public class GameOver
{
public static void main(String[] args)
{
System.out.println("Game Over, Bye Bye!!!");
}
}


Java objects are organized into categories called packages. Packages include related classes for easy organization. For instance, the java.lang package contains classes that relate to the fundamental design of the Java language. The System class is included in the java.lang package. The java.net package contains classes for creating network applications. The java.util package contains utilities such as a random-number generator and date and time utilities. Currently, the basics Java API includes over 75 packages (containing almost 2,000 classes in all), but we will only need to concern ourselves with a handful of those.

The C++ programmers know how difficult it is to remember which header files go with which functions or classes. Luckily, the Java 2 documentation includes the package name with the class name. That way you can quickly get the proper package to import within your programs. If you know the package name for a particular class you wish to use—just type it in. Otherwise, take a logical guess. If that fails, look up the class name in the online documentation; this only takes a minute and the name of the package for the class is printed right at the top of the page.

One more note about imports. For the above example, you could have imported the System class directly, that is:

import java.lang.System;

This is perfectly fine. However, each time you want to use a different class from the java.lang package, you must add an additional import statement so the class can be found. I generally import the entire package because most programs will use several classes from commonly used packages.

Note: Recall that the Java import keyword is analogous to the #include directive in C++. The only difference is that Java makes no distinction between header and source files. Both the declaration and implementation for Java classes are contained in a single .java file.