Package and import statements

In Java, the package statement is used to explicitly define the package in which the class resides. It groups related types1, providing access protection and namespace management. It must be the first executable line of code in a class or in an interface, and it must appears only once in a java file.

To create a package, use the statement package followed by the name of the package (which should follow the Java Naming Conventions):

package org.programmers.code;

If you do not use the package statement, your class ends in an unnamed package, which in Java is called the default package. The types (classes, interfaces, enumerations and annotations) that belongs to the default package can’t be used in a named package (regardless of whether they are defined within the same directory or not).

Classes and interfaces defined in the same package can use each others without prefixing their name with the package name or without import them by using the import statement. In order to use a class from another package, a developer must import that class using the import statement:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

In the above example, I imported three classes (BufferedReader,  IOException and InputStreamReader) into my code. You can also import all classes from a java package, using * placeholder. In the following example, all classes from java.io package are imported:

import java.io.*;

“NOTE : The classes from sub-packages of java.io are not imported!”

“The package and import statement apply to all classes and interfaces defined in a java source code file.”

Take away : In Java, all classes are part of a package.

You may wanna check the rules to remember when defining a package statement.

“NOTE : The import statement doesn’t embed the content of the imported class into the class in which is used! It just allow the java developer to use simple names instead of fully qualified names for classes, interfaces, enumerations and annotations defined in separate packages.”


1 types. Here, types refer to classes, interfaces, enumerations and annotations. Enumerations and annotations are not for Java Certification OCA 7 SE Programmer I exam.

Add a Comment

Your email address will not be published.