Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 07 / Topic 3 of 7

Compiling and running a multi-file, multi-package program

javac can take several files, across several packages, in one call. -d <folder> tells it where to write the compiled .class files — and under -d, javac always recreates the right package folders, no matter where the source files were:

$ javac -d out billing/Invoice.java billing/util/Formatter.java Main.java
$ find out -type f | sort
out/Main.class
out/billing/Invoice.class
out/billing/util/Formatter.class

You don't have to list every file by hand. If one .java file imports a class whose source sits in the expected folder (package folders matching, as in Chapter 2), javac finds and compiles it automatically:

$ javac -d out billing/Invoice.java Main.java
$ find out -type f | sort
out/Main.class
out/billing/Invoice.class
out/billing/util/Formatter.class

Formatter.java was never named on the command line — javac followed the import billing.util.Formatter; line in Main.java, looked for billing/util/Formatter.java relative to the current folder, found it (because the folders matched the package, per Chapter 2), and compiled it too. This is also exactly why mismatched folders broke in Chapter 2: the same automatic lookup had nowhere correct to look.

To run the compiled program, java needs the classpath: the folder (or folders) where it should look for .class files, given with -cp. Then you name the class to run by its fully qualified name:

$ java -cp out Main
Asha owes ₹17,600.50

Main has no package, so its fully qualified name is just Main. A class in a package is always run by its full dotted name, as Chapters 6–7 show (java -cp out todoapp.TodoApp, not java -cp out TodoApp).

Flag On Means
-d <folder> javac write compiled .class files here, inside their package subfolders
-cp <folder> javac or java look here for .class files this command needs (to compile against, or to run)

🔍 Going deeper: -cp can list several locations separated by : on macOS/Linux (; on Windows), for example -cp out:lib/driver.jar once Stage 2 Part 11 adds an external jar. For Stage 1, one output folder is always enough.

Done here? The practice set for Part 7 — including the solutions — is on the part page.

Search the guide