Java Import Statement

As the Java programming language contains a vast array of functionality, it is split up in to Packages, each of which contain a number of related Classes from a functionality point of view. The benefit of this is that a Java program need only include the Packages that contains the functionality it requires to run and nothing more. User defined classes, such as the ‘Hello’ class written in the previous section, can also be placed in to a Package as shown below.

package greeting;

public class Hello {

   public static void main(String[] args) {

      System.out.print("Hello World!");

   }

}

By convention organisations often name packages the reverse of their domain name followed by a descriptive name for its contents, so the above package name could be re-written as follows.

package com.stuartsplace.greeting;

As an example, if a console application is being developed with both input from the user as well as output, the functionality within the ‘Console’ class, which is included in the ‘java.io’ package, will be needed. The following ‘import’ statement will allow the use of the functionality within the ‘Console’ class. All ‘import’ statements need to be included after the package statement, but before the class is defined.

import java.io.Console;

It is also possible to import all of the classes within a package at once by using a wild card, however, this should be used with caution as it can create compile errors where two classes exist of the same name in different packages that are being used.

import java.io.*;

If you are using an Integrated Development Environment, or IDE, such as IntelliJ IDEA, a warning is produced where a class is being used that hasn’t been imported.