A Tutorial on importing packages in Java

By: Emiley J Emailed: 1766 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Given that packages exist and are a good mechanism for compartmentalizing diverse classes from each other, it is easy to see why all of the built-in Java classes are stored in packages. There are no core Java classes in the unnamed default package; all of the standard classes are stored in some named package. Since classes within packages must be fully qualified with their package name or names, it could become tedious to type in the long dot-separated package path name for every class you want to use. For this reason, Java includes the import statement to bring certain classes, or entire packages, into visibility. Once imported, a class can be referred to directly, using only its name. Theimport statement is a convenience to the programmer and is not technically needed to
write a complete Java program. If you are going to refer to a few dozen classes in your application, however, the import statement will save a lot of typing.

In a Java source file, import statements occur immediately following the package statement (if it exists) and before any class definitions. This is the general form of the importstatement:

import pkg1[.pkg2].(classname|*);

Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package inside the outer package separated by a dot (.). There is no practical limit on the depth of a package hierarchy, except that imposed by the file system. Finally, you specify either an explicit classname or a star (*), which indicates that the Java compiler should import the entire package. This code fragment shows both forms in use:

import java.util.Date;
import java.io.*;
Caution: The star form may increase compilation time—especially if you import several large packages. For this reason it is a good idea to explicitly name the classes that you want to use rather than importing whole packages. However, the star form has absolutely no effect on the run-time performance or size of your classes.

All of the standard Java classes included with Java are stored in a package called java. The basic language functions are stored in a package inside of the java package called java.lang. Normally, you have to import every package or class that you want to use, but since Java is useless without much of the functionality in java.lang,it is implicitly imported by the compiler for all programs. This is equivalent to the following line being at the top of all of your programs: 

import java.lang.*;

If a class with the same name exists in two different packages that you import using the star form, the compiler will remain silent, unless you try to use one of the classes. In that case, you will get a compile-time error and have to explicitly name the class specifying its package. Any place you use a class name, you can use its fully qualified name, which includes its full package hierarchy. For example, this fragment uses an import statement:

import java.util.*;
class MyDate extends Date {

The same example without the import statement looks like this:

class MyDate extends java.util.Date {

When a package is imported, only those items within the package declared as public will be available to non-subclasses in the importing code. For example, if you want the Balance class of the package MyPack shown earlier to be available as a stand-alone class for general use outside of MyPack, then you will need to declare it as public and put it into its own file, as shown here:

package MyPack;
/* Now, the Balance class, its constructor, and its
show() method are public. This means that they can
be used by non-subclass code outside their package.
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
public void show() {
System.out.print("—> ");
System.out.println(name + ": $" + bal);

As you can see, the Balance class is now public. Also, its constructor and its show( ) method are public, too. This means that they can be accessed by any type of code outside the MyPack package. For example, here TestBalanceimports MyPack and is then able to make use of the Balance class:

import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()

As an experiment, remove the public specifier from the Balanceclass and then try
compiling TestBalance. As explained, errors will result.

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

it was very usefull.....thanks :)

View Tutorial          By: qwerty at 2010-04-04 05:48:07
2. View Comment

i am confused with importing a package.is it equivalent to including header files in c or c++ or is there any difference.

View Tutorial          By: amit at 2011-07-04 04:16:04
3. View Comment

It is the same as #include

View Tutorial          By: Ballu at 2011-07-04 06:42:55
4. View Comment

is it possible to import one user package inside another user package??

View Tutorial          By: vivek imman at 2011-11-01 12:09:40
5. View Comment

good info to create package

View Tutorial          By: Nirdesh at 2012-10-01 03:45:02
6. View Comment


View Tutorial          By: Rini at 2013-01-08 10:44:54
7. View Comment

i want to know when we're importing a package , will the size of a class (that is importing the package) get increased ? will the classes that are present inside the package gets compiled again ?

View Tutorial          By: bilal ahmad at 2013-02-14 14:11:24
8. View Comment

how to import myownclass into another class same package. please solve this form me i'm waiting i want to solve my task. thanks

View Tutorial          By: rana at 2013-04-19 17:32:08
9. View Comment

this really helps me alot :)

View Tutorial          By: liezl at 2014-08-08 13:38:58
10. View Comment

This example has helped me a lot.! kudos to the writer. A very well done job!

View Tutorial          By: Disha Sareen at 2014-12-24 09:30:12
11. View Comment

i want to how to run a package and compile also

View Tutorial          By: sandhya at 2015-06-25 09:04:03

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Emiley J
Password must include both numeric and alphabetic characters - Magento
What is Hadoop?
Returning multiple values from a web service
Tomcat and httpd configured in port 8080 and 80
Java Webservices using Netbeans and Tomcat
Java WebService connected to Database
How to Deploy a Java Web Service
Call a webservice in Java
Java WebService - Create your first web service in Java
package javax.jws does not exist
Getting Started with Android
HTML5 Location - getCurrentPosition() in HTML5
HTML5 Canvas - Using Canvas in HTML5
HTML5 - Introduction
HTML5 Video - Handling video in HTML5

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
A Serialization Example in Java
Type Casting in Java
instanceof sample program in Java
FilenameFilter - sample program in Java
Using One-Dimensional Arrays in Java
Method Overriding in Java
indexOf( ) and lastIndexOf( ) in Java
The java Buzzwords
Write to a file in Java - Sample Program
What is Java?
FileReader and FileWriter example program in Java
A Tutorial on importing packages in Java
How to use ArrayList in Java
Extract characters in Java
XML and Java - Parsing XML using Java Tutorial
Most Emailed Articles (in Java)
Converting a number into its equalant value in words in Java
java.lang.reflect package
Disadvantages of using Native methods in Java
What is UCS? What is ISO 10646?
Generating Your Key Pair example using keytool in Java
Operator Precedence in Java
PushbackReader sample program in Java
concat(), replace(), and trim() Strings in Java
instanceof sample program in Java
Use of - new - in Java
The Benefits of OOP
Increment and Decrement Operator
Characters in java
The continuing Revolution of java
Why java is important to the Internet