[   ^ to index...   |   <-- previous   ]

Package naming conventions

A package X.Y has no relationship to package X or package X.Y.Z. The convention of including dots to delimit major categories of classes is only a convention. The dot has no effect on the meaning of the name. In this way, it's a "one-level" module system: all modules are at the same level, but some modules have dots in their names.

Also by convention, professional Java programmers name their packages beginning with the backwards Internet domain name of their institution, to avoid conflicts. So, in theory, I would put all my personal Java sources in packages whose names begin with edu.washington.cs.klee.

Packages, files, directories, JARs

Where classes must go in source files

Sun's compiler will complain if you try to put more than one publicly-visible class in a source file. You can put as many package-visible classes in a source file as you want, but even for these I prefer to put each class in its own file.

Where source files must go in the directory tree

Most Java implementations have some constraints on where classes should be located. Sun's compiler and JVM both require that the file and directory structure mirror the package names. So, in the previous example, you would have to put the source files as follows:

    (ROOT)
         |---whales/
                   |---KillerWhale.java
                   |---baleen/
                             |----HumpbackWhale.java

But where is (ROOT)?

There is an "environment variable" named CLASSPATH, which contains a colon-separated list of directories. Sun's compiler consults CLASSPATH to find all the (ROOT) directories from which it should begin searching. To set an environment variable in Unix C shell, use setenv, for example:

    % setenv CLASSPATH ${HOME}/java:${HOME}/lib/java:/usr/lib/jdk/java

You can also set the classpath when you run javac:

    % javac -classpath ${HOME}/mystuff.jar

Hey, mystuff.jar doesn't sound like a directory name that Keunwoo would choose...

It's not. Passing around a big tree directory structure with classfiles scattered around turned out to be an inconvenient way to distribute applications. So, Sun created the JAR file format, which is a lot like a ZIP file. When you put a JAR file in the classpath, the JVM will automatically unpack it on the fly and treat it as if it were a directory. You can read more about creating JARs in Sun's tools documentation.


Keunwoo Lee
Last modified: Wed May 23 22:20:43 PDT 2001