Sub topic 12
Compiling and Running Packaged Code
This chapter assumes you can write a class with a main method, know the package and import syntax from the earlier chapters, and can use a terminal. It covers how javac and java find your files once code lives in packages. Most errors beginners hit with packages come from mixing up the source path, the output directory, and the classpath.
The project layout
The examples use a small shop program with two classes in two packages. The source tree looks like this:
project/
src/
com/example/shop/Main.java
com/example/shop/model/Product.java
out/ (created by javac)The directory names under src must match the package names. Product.java declares package com.example.shop.model;, so it sits in src/com/example/shop/model/.
Here are the two source files.
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;
}
}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());
}
}Compiling with `javac -d`
Run the compiler from the project directory:
javac -d out src/com/example/shop/Main.java src/com/example/shop/model/Product.java
java -cp out com.example.shop.MainThe first command compiles both files. The -d out option sets the destination directory for class files. The compiler creates one subdirectory per package segment, so the result is:
out/
com/example/shop/Main.class
com/example/shop/model/Product.classThe class file directories mirror the packages, just as the source directories do. If out does not exist, javac may fail with an error such as directory not found: out. Create it first with mkdir out. Recent JDK versions create it for you, but older ones do not, so creating it yourself is safe.
Without -d, javac writes each .class file next to its .java file. That works for one-off experiments but mixes sources with build output. It also makes the java command harder to run, because the classpath must then point at the source tree.
Running with `java -cp`
The java command takes a fully qualified class name, not a file path:
java -cp out com.example.shop.MainTwo things matter here.
-cp out(or-classpath out) tells the JVM where the root of the package tree is. The JVM looks forcom/example/shop/Main.classunderout.com.example.shop.Mainuses dots, not slashes, and has no.classextension.
The following table lists common wrong commands and what goes wrong.
| Command | Result |
|---|---|
| `java out/com/example/shop/Main` | Error: could not find or load main class |
| `java -cp out Main` | `ClassNotFoundException` or "could not find main class", because `Main` is not in the default package |
| `java -cp out/com/example/shop com.example.shop.Main` | The classpath root is one level too deep, so the JVM looks for `out/com/example/shop/com/example/shop/Main.class` |
| `java -cp out com.example.shop.Main.class` | The JVM treats `Main.class` as a class named `class` inside package `...Main` |
A classpath entry always names the directory that holds the top of the package tree. It never names a package directory inside the tree.
How the compiler finds other classes
Main refers to Product, yet in a command like javac -d out src/com/example/shop/Main.java you may leave Product.java off the list. The compiler can still succeed because it searches for missing types.
It uses two search locations:
- The class path (
-cpor-classpath), which holds compiled.classfiles and JARs. - The source path (
-sourcepath), which holds.javafiles. If you do not set it, the compiler searches the class path for source files too.
For a needed type such as com.example.shop.model.Product, the compiler converts the name to the relative path com/example/shop/model/Product and looks under each search root for a .class or .java file. This is why the directory layout must match the package.
So this command works without listing Product.java:
javac -d out -sourcepath src src/com/example/shop/Main.javaThe compiler reads Main.java, sees the import, finds src/com/example/shop/model/Product.java through the source path, and compiles it as well. Listing every file by hand does not scale, so most projects use one of these approaches:
- A build tool such as Maven or Gradle, which handles the paths for you.
- A file list passed with an
@argument file. - Your IDE, which runs
javacinternally.
The @ form looks like this on Linux or macOS:
find src -name "*.java" > sources.txt
javac -d out @sources.txt
java -cp out com.example.shop.MainOn Windows, use dir /s /b src\*.java > sources.txt instead of find.
Adding libraries to the classpath
When your program depends on JAR files, list them in the classpath along with your own output directory. Entries are separated by : on Linux and macOS and by ; on Windows.
javac -d out -cp lib/gson.jar src/com/example/shop/Main.java
java -cp "out:lib/gson.jar" com.example.shop.MainQuote the classpath so the shell does not interpret ; or *. A wildcard such as lib/* matches every JAR in lib, but not class files or subdirectories:
java -cp "out:lib/*" com.example.shop.MainThe -cp option overrides the CLASSPATH environment variable. If you set neither, the default classpath is the current directory (.). Once you pass -cp out, the current directory is no longer included. If you also need it, add . yourself, as in -cp "out:.".
Avoid the CLASSPATH environment variable in new work. A global setting affects every program on the machine and causes hard-to-trace behavior when two projects need different libraries.
Seeing the whole process
The next diagram shows how the pieces connect.
Common errors
Package-related compile and run errors fall into a few groups. Learn to read them by their message.
"package does not exist"
Main.java:3: error: package com.example.shop.model does not exist
import com.example.shop.model.Product;The compiler could not find that package on the class path or source path. Check three things:
- The directory structure under the search root matches the package name, including capitalization.
- You are running
javacfrom the directory you think you are in. - You passed
-sourcepathor-cpwhenProductis not listed on the command line.
"class X is public, should be declared in a file named X.java"
A public class must live in a file with the same name. This error also appears if you misspell the file name or its case.
"could not find or load main class"
This usually means one of the following:
- The classpath root is wrong (see the table above).
- You gave a file path instead of a class name.
- The class has a
packagedeclaration but you ran it by its simple name. - Compilation failed earlier, so no
.classfile exists.
"wrong name" errors
error: class file contains wrong class: com.example.shop.MainThe .class file was found at a path that does not match the package inside it. This happens when you move class files by hand or point -cp at the wrong level.
Compiling from inside the package directory
A frequent mistake is to cd into src/com/example/shop and run javac Main.java. The compile may succeed, but only because the class file lands next to the source. Running it then fails:
cd src/com/example/shop
javac Main.java
java MainThe last command fails with an error such as Could not find or load main class Main, or a NoClassDefFoundError that says the expected name is com/example/shop/Main. The JVM wants the full name, and the classpath root must be src. The correct form is:
cd project
java -cp src com.example.shop.MainThat only works if the .class files are in src, which is why using -d out from the project root is the cleaner habit.
Running a single source file
Since JDK 11, java can compile and run a single source file in memory:
java src/com/example/shop/Main.javaThis is convenient for scripts, but it does not follow the package layout. The launcher compiles only that one file, so it fails if Main needs Product from another file. JDK 22 and later add support for multi-file source launching in some cases, but a normal javac build is the dependable way to run multi-package code.
A first look at JARs
A JAR file is a ZIP archive of class files, with an optional manifest. You can package the output directory and run it:
jar --create --file shop.jar --main-class com.example.shop.Main -C out .
java -jar shop.jarThe -C out . part tells jar to change into out and add everything there, so the package directories sit at the root of the archive. If you left out -C out, the entries would be prefixed with out/, and the JVM would not find the classes. You can also put a JAR on the classpath like a directory: java -cp shop.jar com.example.shop.Main.
Modules, which group packages with explicit dependencies, are introduced in a later chapter. The module path (-p) works alongside the classpath, and the same -d and fully qualified name rules apply.
Summary of the rules
javac -d <dir>writes class files into directories that mirror the packages.java -cp <root> <fully.qualified.Name>needs the root of the package tree, not a package directory.- The compiler finds unlisted classes through
-sourcepathor the class path. - A classpath entry is a directory or JAR. Separate entries with
:or;depending on the platform. - Setting
-cpreplaces the default of..
Exercise
You compiled with javac -d build src/app/util/Tool.java, where Tool.java declares package app.util; and has a main method. Which command runs it, and why does java -cp build/app/util Tool fail?
Show answer
Run java -cp build app.util.Tool. The classpath must name build, the root of the package tree, and the class is identified by its fully qualified name app.util.Tool. With -cp build/app/util Tool, the JVM looks for build/app/util/Tool.class and finds the file, but the class inside declares the name app.util.Tool, so it reports a wrong-name error (NoClassDefFoundError) instead of running.
Exercise
A project has src/org/demo/App.java (package org.demo) that imports org.demo.data.Loader from src/org/demo/data/Loader.java. You run javac -d out src/org/demo/App.java and it succeeds. Why does it work, and what does the compiler search to find Loader?
Show answer
With no -sourcepath, the compiler searches the class path for source files as well as class files, and the default class path is the current directory. From the project root it converts org.demo.data.Loader to org/demo/data/Loader, which does not exist at the root, so this succeeds only if the source tree is reachable. Running from the project root with src unreachable would fail; the reliable command is javac -d out -sourcepath src src/org/demo/App.java, which lets the compiler find src/org/demo/data/Loader.java and compile it too.