Sub topic 4
Matching packages to directories
This chapter assumes you can write and run a basic Java class with a main method, and that you know class, method and field syntax. It also assumes you can compile from a command line or an IDE. You have seen the package declaration. Here you will see how it ties to folders on disk, and what breaks when the two disagree.
The rule in one sentence
A class declared in package a.b.c is stored in a directory path a/b/c, relative to a root directory. This holds for source files and for compiled class files. The root is called the source root (for .java files) or the class path entry (for .class files).
Each dot in the package name becomes a directory separator. The class com.example.shop.model.Product therefore lives at:
src/com/example/shop/model/Product.javaas sourceout/com/example/shop/model/Product.classonce compiled
Here src is the source root and out is the output root.
A worked layout
Take the Product class from the earlier chapter:
package com.example.shop.model;
public class Product {
private final String name;
private final double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}Add a Main class in the parent package, com.example.shop:
package com.example.shop;
import com.example.shop.model.Product;
public class Main {
public static void main(String[] args) {
Product p = new Product("Pen", 1.5);
System.out.println(p.getName() + " costs " + p.getPrice());
}
}The project tree looks like this:
project/
src/
com/
example/
shop/
Main.java
model/
Product.javaThe source root is src. The path from src to each file, minus the file name, is the package name with dots replaced by slashes. Main.java sits in com/example/shop, so its package is com.example.shop. Product.java sits one level deeper in model, so its package is com.example.shop.model.
Source tree and class tree mirror each other
When you compile with -d, javac creates a directory tree under the output directory that mirrors the packages:
javac -d out src/com/example/shop/Main.java src/com/example/shop/model/Product.javaThe result is:
out/
com/
example/
shop/
Main.class
model/
Product.classYou did not create any of these directories. javac derives them from each package declaration and creates them as needed. Without -d, javac writes each .class file next to its .java file. That works for a quick test, but it mixes generated files with your source, so real projects always use -d.
The class path entry works the same way. When you run java -cp out com.example.shop.Main, the JVM takes the fully qualified name, replaces dots with slashes, appends .class, and looks for out/com/example/shop/Main.class. The class loader does no searching beyond that. If the file is not at that exact relative path, the class is not found.
The table summarizes the mapping.
| Item | Where it comes from | Example |
|---|---|---|
| Package name | `package` declaration | `com.example.shop.model` |
| Relative directory | Package name, dots become separators | `com/example/shop/model` |
| Source file | Source root + directory + `Name.java` | `src/com/example/shop/model/Product.java` |
| Class file | Output root + directory + `Name.class` | `out/com/example/shop/model/Product.class` |
| Fully qualified name | Package name + `.` + class name | `com.example.shop.model.Product` |
What the compiler actually enforces
The layout rule is stricter at some points than others, and this is a common source of confusion.
- File name for public classes. A public top-level class must be declared in a file with the same name plus
.java. Declaringpublic class ProductinItem.javais an error:class Product is public, should be declared in a file named Product.java. This rule has nothing to do with directories. - Directory of a file you pass explicitly. If you list a source file on the javac command line, javac compiles it using the package declared inside it. It does not check that the file sits in the matching directory. With
-d out, the class file still goes into the directory the declaration implies. - Directory of a file javac must find itself. When your code refers to a class you did not list, javac searches for it. It looks on the class path, or on the source path if you give
-sourcepath, and it uses the package-to-directory rule to decide where to look. If the source file is in the wrong directory, javac does not find it. - Directory of a class file at run time. The JVM relies on the rule fully. It finds a class only at the path derived from its name.
Because of point 3, you can compile the whole program by naming only the entry point and giving the source root:
javac -d out -sourcepath src src/com/example/shop/Main.javajavac sees import com.example.shop.model.Product, looks for src/com/example/shop/model/Product.java, and compiles it too. If you moved Product.java to src/Product.java, this command would fail with package com.example.shop.model does not exist, even though the file is present.
Common errors
Running from the wrong directory
Suppose you compiled to out and then try this:
java -cp out/com/example/shop MainThe JVM finds Main.class in that directory, reads the class name stored inside it (com/example/shop/Main), and sees that it differs from the name you requested. You get a NoClassDefFoundError whose message contains wrong name. The fix is to put the root on the class path and give the full name:
java -cp out com.example.shop.MainUsing slashes or the `.class` suffix
Give java the dotted name, not a path:
java -cp out com.example.shop.Mainworks.java -cp out com/example/shop/Mainfails to find the class on current JDKs.java -cp out com.example.shop.Main.classfails, becauseclassis read as a nested class name.
A package declaration that disagrees with the folder
Say you move Product.java to a folder src/com/example/shop/models but leave package com.example.shop.model; unchanged. Compiling the file by name succeeds, and the class file lands in out/com/example/shop/model/. The mismatch surfaces later, when someone uses -sourcepath or an IDE and gets "package does not exist" errors. Keep the declaration and the folder in agreement from the start.
Misspelled or differently cased directories
On Linux, Com/example and com/example are different directories. On Windows and default macOS file systems they are the same. A mismatch can compile on one machine and fail on another. Package names are conventionally all lower case, which avoids the problem.
Nesting in the file system is not nesting in Java
The directory tree is hierarchical, but packages are not. com.example.shop and com.example.shop.model are two separate, unrelated packages. The second sits in a subdirectory of the first, but that gives it no special access to the first, and importing one does not import the other.
For example, import com.example.shop.*; brings in the classes in com.example.shop only. It does not bring in Product, because Product is in com.example.shop.model. This is why Main above needed its own import for Product. The hierarchy in names is for organization and for avoiding clashes, and the language ignores it when resolving names or checking access.
Platform details
- The
packagedeclaration always uses dots. The command line uses your operating system's path separators, so on Windows you writesrc\com\example\shop\Main.java. javac also accepts forward slashes there. - The class path separator is
:on Linux and macOS and;on Windows. For-cp out:lib/util.jar, each entry is a root, and the package path is appended to each root in turn. - Since JDK 11 you can run a single source file directly with
java Main.java. That mode compiles in memory and does not need the directory layout. Once a program has several packages, return to the normal layout.
Practical habits
- Pick one source root, such as
src, and keep every package below it. - Create the folder path first, then the file, or let your IDE create it when you create the package.
- Always compile with
-dto a separate output directory such asout. - Run with the output root on the class path and the fully qualified name of the main class.
- If a class cannot be found, check three things in order: the
packageline, the directory that holds the file, and the root you gave javac or-cp.
Exercise
You have the file src/app/util/Strings.java containing "package app.util; public class Strings { public static String shout(String s) { return s.toUpperCase() + "!"; } }" and src/app/Main.java containing "package app; import app.util.Strings; public class Main { public static void main(String[] args) { System.out.println(Strings.shout("hi")); } }". Give a javac command that compiles both into out, a java command that runs the program, and the path of the class file created for Strings.
Show answer
Compile with "javac -d out src/app/Main.java src/app/util/Strings.java", or with "javac -d out -sourcepath src src/app/Main.java", which finds Strings.java through the import. Run with "java -cp out app.Main", which prints HI!. The Strings class file is created at out/app/util/Strings.class, because the package app.util maps to the directory app/util under the output root.
Exercise
A teammate moves Strings.java from src/app/util to src/app/helpers but does not change its package line. Does "javac -d out src/app/Main.java src/app/helpers/Strings.java" still work? What about "javac -d out -sourcepath src src/app/Main.java"?
Show answer
The first command works. Both files are named explicitly, so javac uses the package declared inside Strings.java and writes out/app/util/Strings.class. The second command fails with "package app.util does not exist", because javac looks for src/app/util/Strings.java through the import, and the file is no longer there. The fix is to keep the declaration and the directory in agreement, either by moving the file back or by changing the package line and the import to app.helpers.