Packages in Java: Placement

How is a class or interface placed inside a package?

Overview

A class or interface’s package location is actually not specified by the directory where the source file or bytecode file resides, though the directory location is critical. Instead, each Java class or interface that is in a package declares that in a package statement in the source code. Upon compilation, that package declaration becomes part of the resulting bytecode; in other words, the fully-qualified class or interface name is compiled into the bytecode itself.

Syntax

When the package statement is present in a Java source file, it must be the first statement in the file; it can only be preceded by whitespace and comments (which are ignored by the compiler).

The form of the package statement is simple:

package {packagename[.subpackagename[...]]};

Placeholders

(Note that the braces and brackets are part of the placeholders, and must not appear in the actual package statement.)

packagename

The root-level package name.

subpackagename

Zero or more nested levels of subpackage names.

Example

package edu.cnm.deepdive.codebreaker;

This statement declares that any classes or interfaces defined in the current source file will reside in the edu.cnm.deepdive.codebreaker package—that is, in a codebreaker subpackage inside the deepdive subpackage, which is in the cnm subpackage, which is inside the edu package.

Note that the package statement must be terminated with a semicolon.

Package vs. directory

The directory path where the source file is located must agree with package statement. The directory corresponding to the root-level package may be located inside another directory; however, starting with the root-level package, the directory structure must match the package statement exactly (including letter casing).

The same requirement applies to the bytecode file produced by the Java compiler: If it is not located in a directory path (relative to the class path) corresponding to the package declared in the class or interface, the class loader will either not be able to locate the bytecode file, or will refuse to load it.

Default package

If a class or interface is not placed in a package (i.e. it has no package statement), it will be placed in the default package—essentially, a package with no name. Though it may be tempting just to write all of our code in the default package, that would be a mistake: it would not only make it more difficult to keep the code in a project well-organized, but also significantly limit our flexibility to use the resulting bytecode in future projects.

In any event, use of the default package is not permitted in this bootcamp.