Home           J2EE Concepts           JMS           Java Language           Contact           Back           Next           Bookmark this Page          










Some useful tips related to:
 - health & fitness
 - vehicle care
 - cooking
 - misc household tasks

Packages Overview


Packages are like directories/folders in your file system that help in identifying your class uniquely. Although this analogy isn't a perfect one, but it helps in explaining the concept. Packages provide unique path name to your java class. Thus, packages could be thought of as simple naming conventions.

For e.g., Java keeps its Arrays class in a package named java.util; & the class can be accessed as java.util.Arrays

If you've to create a class named myClass in a package called myPackage; then you would need to do following:
- Create a folder called myPackage
- Then create a .java file named myClass inside that folder
- Include following command at the first line of your .java file:
    package myPackage;
After compilation this class would be referenced AS myPackage.myClass

P.S.: Remember, case is important & directory name(s) must match the package names.


You can create full fledged hierarchies for packages; i.e. your java file would exist somewhere deep inside your folder hierarchy. To define such package in your class, you would need to separate the package names by period.
For e.g., if you've following hierarchy in your file system: pkg1/pkg2/pkg3/pkg4/myClass.java then first line of your myClass.java would be as follows:
package pkg1.pkg2.pkg3.pkg4;
After compilation if you want to run this file, you would issue following command on console:
java pkg1.pkg2.pkg3.pkg4.myClass

The package hierarchy can be as deep as you wish. There is no limit to the no. of levels.

Multiple classes can share same package. As per our imperfect analogy :), multiple files can exist inside same folder. In this case, the first line of all files would contain same package statement. This also means that packages can be looked upon as grouping of classes serving similar purposes.

You would also need to ensure the correct classpath entries. For details on classpath please refer to What is Classpath? section of this site.