Java – the purpose of defining a package in a Java file?

javapackage

I am a newbie and just learned that if I define say

package my.first.group.here;
...

then the Java files that are in this package will be placed under my/first/group/here directory.

What is the main purpose of putting some Java files in a package? Also, if I choose to adopt this, how should I group them?

Thank you


EDIT: For anyone who might have the same question again, I just found this tutorial on packages from Sun.

Best Solution

Let's start with the definition of a "Java package", as described in the Wikipedia article:

A Java package is a mechanism for organizing Java classes into namespaces similar to the modules of Modula. Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time. Programmers also typically use packages to organize classes belonging to the same category or providing similar functionality.

So based on that, packages in Java are simply a mechanism used to organize classes and prevent class name collisions. You can name them anything you wish, but Sun has published some naming conventions that you should use when naming packages:

Packages

The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.

Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.

Examples:

  • com.sun.eng

  • com.apple.quicktime.v2

  • edu.cmu.cs.bovik.cheese