Importing classes

Classes can be referenced in code by using the fully qualified class name. For instance, when using ArrayList in a method, code can be written like this:

    java.util.ArrayList list = new java.util.ArrayList();

This requires a lot of keystrokes, even for a language that is known for its verbosity. Of course, Java has a solution. Using the import keyword, classes can be referenced by the class name only. The most basic form looks like this:

    import java.util.ArrayList;
class Demo {
ArrayList list = new ArrayList();
}

The code of the method can now simply use the ArrayList class name and does not have to provide the fully qualified class name any longer. Import statements must appear after the package keyword, if present, but before the first class definition. It is not possible to specify multiple packages on a single import statement.

When name clashes occur (which happens when the same class name is used in two or more packages), you can import only one of them. Plus, you have to use the fully qualified class name in the code for others.

It's also possible to import all the classes from a package with a single line:

    import java.util.*;

This form is not really recommended in source code intended for larger systems, though. It can increase the chances for unexpected class name clashes. Note that only the classes from the specified packages are imported. Subpackages remain unaffected and have to be imported separately. For example, java.util.concurrent is a package that contains utility classes for concurrent programming. To load classes from both the packages, import statements for both the packages are required.

All the classes of the java.lang package are always imported implicitly and are available at any time.