Java Modules: Benefits, module-info.java, Compiling, Running and Packaging (OCP 21)
Your first Java modules for the OCP 21 exam: why the module system exists, its benefits, writing module-info.java, the folder layout, compiling with javac -p and -d, running with java -p and -m, packaging a module JAR, and connecting two modules with exports and requires.
kvi5hnuCode Sprout team member11 min readOn this page
Packages group classes, and JAR files group packages. For large applications that isn't enough. On the class path, every public class in every JAR can see every other one. Nothing records which JARs need which, so a missing or duplicate JAR shows up only as a NoClassDefFoundError deep inside a running program. Developers call this mess "JAR hell".
The Java Platform Module System (JPMS), added in Java 9, adds a level above packages. A module is a named group of packages plus a descriptor file, module-info.java, that states which packages the module shares and which other modules it needs. The module system includes:
- a format for module JARs (a JAR with
module-info.classat its root), - the JDK itself split into modules, such as
java.base,java.sqlandjava.logging, - new command-line options for
javac,java,jarand other tools.
Modules are optional. Code on the class path still works exactly as before. The exam, however, expects you to know the module commands by heart.
Why use modules?
Know these six benefits for the exam:
| Benefit | What it means |
|---|---|
| Better access control | A module can keep a package to itself. Even public classes in a package that isn't exported are invisible to other modules. This is a fifth level of encapsulation on top of private, package access, protected and public. |
| Clearer dependency management | Each module lists the modules it requires. A missing module is reported when the program starts, not when the class is first used at some later point. |
| Custom Java builds | jlink can produce a runtime that contains only the JDK modules your program needs, instead of the whole JDK. |
| Improved security | Code that isn't in your custom runtime can't be attacked. A vulnerability in a module you left out doesn't affect you. |
| Improved performance | A smaller runtime starts faster and uses less memory. |
| Unique package enforcement | A package may come from only one module. Two modules that contain the same package (a split package) are rejected, so you always know which code is running. |
The module declaration: module-info.java
The smallest possible module needs one class and one descriptor. Here's a module named garden.water with a single class:
package garden.water;
public class Sprinkler {
public static void main(String... args) {
System.out.println("Beds watered");
}
}
// module-info.java
module garden.water { }
Rules for the declaration:
- The file is named
module-info.javaand goes in the root folder of the module, next to the top-level package folders, not inside a package. When compiled,module-info.classmust sit at the root of the output folder and of the JAR. - It starts with the keyword
module, notclass,interface,enumorrecord. - The module name follows the same rules as a package name. It may contain dots, but not dashes, and no part may be a reserved word:
garden-waterandgarden.intdon't compile.javacalso warns about a part that ends in a digit, such asgarden.water2. - By convention, the module name matches the package it contains, or the common start of its packages. You can think of
garden.wateras "claiming" thegarden.waterpackage and its subpackages. This is only a convention: the compiler doesn't check it. - The directives inside the braces (covered below and in the next article) can appear in any order. An empty body is legal.
Folder layout
The module lives in its own folder, which this article calls water. Package folders go under it as usual, and module-info.java is directly inside it. A sibling folder, conventionally named mods, will hold finished module JARs:
water/
├── module-info.java
└── garden/
└── water/
└── Sprinkler.java
mods/

Compiling a module
javac --module-path mods -d water water/garden/water/Sprinkler.java water/module-info.java
-d watersays where to put the class files. Here they go next to the sources in the module folder. Each.classfile ends up in the package folder, andmodule-info.classat the root.--module-path mods(short form-p mods) says where to find other modules this one depends on. This module has no dependencies, so the option could be left out. On modular code, the module path takes the place of the class path.- The rest of the command lists the source files. You can name each file or use a wildcard per folder.
All of these are equivalent:
javac -p mods -d water water/garden/water/*.java water/module-info.java
javac -p mods -d water water/garden/water/*.java water/*.java
javac -p mods -d water water/garden/water/Sprinkler.java water/*.java
javac --module-path mods -d water water/garden/water/Sprinkler.java water/module-info.java
water/*.java matches only module-info.java, because the wildcard doesn't descend into subfolders.
The class path options still exist, with three spellings: -cp, -classpath and --class-path. The module path has two: -p and --module-path.
javac option | Short form | Long form |
|---|---|---|
| Output folder for class files | -d <dir> | (none) |
| Where to find other modules | -p <path> | --module-path <path> |
Running a module
java --module-path water --module garden.water/garden.water.Sprinkler
java -p water -m garden.water/garden.water.Sprinkler
The value of --module (short form -m) is the module name, a slash, then the fully qualified class name. Here the module and package are both called garden.water, so the name appears twice. That's common, but the two parts mean different things.
java option | Short form | Long form |
|---|---|---|
| Module (and main class) to run | -m <name> | --module <name> |
| Where to find modules | -p <path> | --module-path <path> |
Common mistakes, all verified:
java -p mods -m garden.water.Sprinkler: the whole string is taken as a module name, so it fails withFindException: Module garden.water.Sprinkler not found.java -p mods garden.water/garden.water.Sprinkler: without-m,javalooks for a class with that odd name and reportsClassNotFoundException.java -m garden.water/garden.water.Sprinkler -p mods: everything after the main class is passed tomainas program arguments, so-p modsis ignored and the module isn't found.java -p mods -m garden.waterwithout a class name works only if the module JAR records a main class (jar --main-class ...). Otherwisejavareplies that the module "does not have a ModuleMainClass attribute".
Running a class doesn't require exporting its package. Exports control what other modules can compile against. The launcher can start a main method in any package of the module.
Packaging a module JAR
jar -cvf mods/garden.water.jar -C water/ .
Nothing here is module-specific. -c creates an archive, -v lists what is added, and -f names the file. -C water/ switches to that folder before adding files, and the final . means "everything in it". Because module-info.class ends up at the root of the JAR, the result is a module JAR.
Run the packaged module the same way, now pointing the module path at mods:
java -p mods -m garden.water/garden.water.Sprinkler
A module path entry can be a folder of module JARs, a single module JAR, or a folder of compiled classes (an exploded module), as in the previous section.
If module-info.class isn't at the root of the JAR, Java doesn't treat the JAR as the module you meant. It treats it as an automatic module named after the file (garden.water.jar gives garden.water) whose packages follow the wrong folder structure (water.garden.water), so -m garden.water/garden.water.Sprinkler fails with "Could not find or load main class garden.water.Sprinkler in module garden.water". Automatic modules are covered in article 77.
Connecting two modules: exports and requires
A second module, garden.plants, wants to call Sprinkler:
package garden.plants.care;
import garden.water.Sprinkler;
public class Schedule {
public static void main(String[] args) {
Sprinkler.main();
System.out.println("Schedule ready");
}
}
Two declarations are involved:
module garden.water {
exports garden.water; // share this package with other modules
}
module garden.plants {
exports garden.plants.care;
requires garden.water; // this module needs garden.water
}
exports <package>makes a package's public types available to other modules. A package that isn't exported is private to its module, howeverpublicits classes are.requires <module>says this module depends on another. It names a module, whileexportsnames a package.
Both are needed. Missing either gives a compile error:
| What's missing | javac error |
|---|---|
garden.water doesn't export garden.water | package garden.water is not visible |
garden.plants has no requires garden.water | package garden.water is not visible |
| The required module isn't on the module path | module not found: garden.water |
exports names a package with no classes in the module | package is empty or does not exist |
The same check happens when the program starts. If garden.water.jar is removed from mods before running garden.plants, the JVM stops before main is called, with java.lang.module.FindException: Module garden.water not found, required by garden.plants. This is the "clearer dependency management" benefit in action.
To build several modules by hand, compile each one with -p mods so that it can find the JARs already built, then package it into mods. Build them in dependency order, starting with modules that require nothing:
javac -p mods -d plants plants/garden/plants/care/*.java plants/module-info.java
jar -cvf mods/garden.plants.jar -C plants/ .
java -p mods -m garden.plants/garden.plants.care.Schedule
Every module implicitly requires java.base, the module that contains java.lang, java.util and the other core packages. You never need to write requires java.base;, though it's allowed.
What's current
- JPMS has been part of Java since Java 9 (2017), and the commands in this article haven't changed since. Everything here applies to Java 21 and to Java 25.
- Real projects build modules with Maven or Gradle, not by hand. The exam still tests the raw
javac,javaandjarsyntax. javac --module-source-pathcan compile many modules in one command. It isn't on the exam.- Java 25 finalized module import declarations (
import module java.base;), which import every package a module exports. They aren't part of the Java 21 exam. Article 92 covers them.
Exam traps from this article
A complete example
This program builds the two garden modules for real, using the same javac and jar tools you'd type at the command line, which it calls in-process through java.util.spi.ToolProvider. It writes the sources to a temporary folder, shows the compile error for a missing exports, fixes it, builds both module JARs, prints their descriptors, and starts garden.plants in a new module layer, as java -p mods -m ... would. It then shows the startup failure when a required module is missing. Finally it deletes the temporary folder. It needs a full JDK, which includes javac.
import java.io.*;
import java.lang.module.*;
import java.nio.file.*;
import java.util.*;
import java.util.spi.ToolProvider;
public class Solution {
static Path root;
// Writes one source file under the temporary project folder.
static void write(String file, String code) throws IOException {
Path p = root.resolve(file);
Files.createDirectories(p.getParent());
Files.writeString(p, code);
}
// Runs javac or jar in-process, exactly like typing the command.
static int run(String tool, String... args) {
System.out.println("$ " + tool + " " + String.join(" ", args));
String[] full = Arrays.stream(args)
.map(a -> a.contains("/") ? root.resolve(a).toString() : a)
.toArray(String[]::new);
var err = new StringWriter();
int code = ToolProvider.findFirst(tool).orElseThrow()
.run(new PrintWriter(Writer.nullWriter()), new PrintWriter(err), full);
err.toString().lines()
.filter(l -> l.contains("error:"))
.forEach(l -> System.out.println(" " + l.substring(l.indexOf("error:"))));
return code;
}
// "mandated java.base" or just "garden.water", without version details.
static String describe(ModuleDescriptor.Requires r) {
var words = new ArrayList<String>();
r.modifiers().forEach(m -> words.add(m.toString().toLowerCase(Locale.ROOT)));
words.add(r.name());
return String.join(" ", words);
}
static void deleteTree(Path dir) throws IOException {
try (var paths = Files.walk(dir)) {
for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) {
Files.delete(p);
}
}
}
public static void main(String[] args) throws Exception {
root = Files.createTempDirectory("garden");
try {
System.out.println("== 1. Module garden.water (exports nothing yet)");
write("water/garden/water/Sprinkler.java", """
package garden.water;
public class Sprinkler {
public static void main(String... args) {
System.out.println(" [garden.water] Beds watered");
}
}
""");
write("water/module-info.java", "module garden.water { }\n");
Files.createDirectories(root.resolve("mods"));
run("javac", "-p", "mods/", "-d", "water/",
"water/garden/water/Sprinkler.java", "water/module-info.java");
run("jar", "-cf", "mods/garden.water.jar", "-C", "water/", ".");
System.out.println("\n== 2. Module garden.plants requires garden.water");
write("plants/garden/plants/care/Schedule.java", """
package garden.plants.care;
import garden.water.Sprinkler;
public class Schedule {
public static void main(String[] args) {
Sprinkler.main();
System.out.println(" [garden.plants] Schedule ready");
}
}
""");
write("plants/module-info.java", """
module garden.plants {
exports garden.plants.care;
requires garden.water;
}
""");
int first = run("javac", "-p", "mods/", "-d", "plants/",
"plants/garden/plants/care/Schedule.java", "plants/module-info.java");
System.out.println(" exit code " + first + " -> garden.water must export its package");
System.out.println("\n== 3. Add 'exports garden.water;' and rebuild");
write("water/module-info.java", "module garden.water {\n exports garden.water;\n}\n");
run("javac", "-p", "mods/", "-d", "water/",
"water/garden/water/Sprinkler.java", "water/module-info.java");
run("jar", "-cf", "mods/garden.water.jar", "-C", "water/", ".");
int second = run("javac", "-p", "mods/", "-d", "plants/",
"plants/garden/plants/care/Schedule.java", "plants/module-info.java");
run("jar", "-cf", "mods/garden.plants.jar", "-C", "plants/", ".");
System.out.println(" exit code " + second);
System.out.println("\n== 4. What the module path now contains");
ModuleFinder finder = ModuleFinder.of(root.resolve("mods"));
finder.findAll().stream()
.map(ModuleReference::descriptor)
.sorted(Comparator.comparing(ModuleDescriptor::name))
.forEach(d -> System.out.println(" " + d.name()
+ " requires " + new TreeSet<>(d.requires().stream().map(Solution::describe).toList())
+ " exports " + new TreeSet<>(d.exports().stream().map(Object::toString).toList())));
System.out.println("\n== 5. Like: java -p mods -m garden.plants/garden.plants.care.Schedule");
ModuleLayer boot = ModuleLayer.boot();
Configuration cf = boot.configuration()
.resolve(finder, ModuleFinder.of(), Set.of("garden.plants"));
ModuleLayer layer = boot.defineModulesWithOneLoader(cf, ClassLoader.getSystemClassLoader());
Class<?> main = layer.findLoader("garden.plants").loadClass("garden.plants.care.Schedule");
main.getMethod("main", String[].class).invoke(null, (Object) new String[0]);
System.out.println(" Schedule lives in module " + main.getModule().getName());
System.out.println("\n== 6. Startup check when garden.water.jar is missing");
ModuleFinder onlyPlants = ModuleFinder.of(root.resolve("mods/garden.plants.jar"));
try {
boot.configuration().resolve(onlyPlants, ModuleFinder.of(), Set.of("garden.plants"));
} catch (FindException e) {
System.out.println(" " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
System.out.println("\n== 7. Modules you already use");
System.out.println(" String is in " + String.class.getModule().getName());
System.out.println(" Solution is in a named module? " + Solution.class.getModule().isNamed());
} finally {
deleteTree(root);
}
}
}
Output:
== 1. Module garden.water (exports nothing yet)
$ javac -p mods/ -d water/ water/garden/water/Sprinkler.java water/module-info.java
$ jar -cf mods/garden.water.jar -C water/ .
== 2. Module garden.plants requires garden.water
$ javac -p mods/ -d plants/ plants/garden/plants/care/Schedule.java plants/module-info.java
error: package garden.water is not visible
exit code 1 -> garden.water must export its package
== 3. Add 'exports garden.water;' and rebuild
$ javac -p mods/ -d water/ water/garden/water/Sprinkler.java water/module-info.java
$ jar -cf mods/garden.water.jar -C water/ .
$ javac -p mods/ -d plants/ plants/garden/plants/care/Schedule.java plants/module-info.java
$ jar -cf mods/garden.plants.jar -C plants/ .
exit code 0
== 4. What the module path now contains
garden.plants requires [garden.water, mandated java.base] exports [garden.plants.care]
garden.water requires [mandated java.base] exports [garden.water]
== 5. Like: java -p mods -m garden.plants/garden.plants.care.Schedule
[garden.water] Beds watered
[garden.plants] Schedule ready
Schedule lives in module garden.plants
== 6. Startup check when garden.water.jar is missing
FindException: Module garden.water not found, required by garden.plants
== 7. Modules you already use
String is in java.base
Solution is in a named module? false
Points to notice:
- The first compile of
garden.plantsfailed with "package garden.water is not visible". The JAR was on the module path, but its package wasn't exported. - After adding
exports garden.water;, the samejavaccommand succeeded with exit code 0. - Each descriptor lists
mandated java.base: the dependency every module has without declaring it. Scheduleran inside modulegarden.plantsand called intogarden.water, exactly asjava -p mods -m garden.plants/garden.plants.care.Schedulewould.- With only
garden.plants.jaravailable, resolution failed withFindException ... required by garden.plantsbefore any code ran. Stringlives in modulejava.base. The program itself runs from the class path, so its class is in an unnamed module.
Common questions
Do I have to use modules in Java 21? No. Programs on the class path work as before. Even then, the JDK itself is modular, and your class-path code runs in the unnamed module (article 77).
Can one JAR contain two modules?
No. A module JAR has exactly one module-info.class at its root, so it holds exactly one module.
Does the module name have to match the package name?
No. It's a strong convention (usually reverse-DNS, like package names), but javac doesn't enforce it.
Is module a reserved word now?
It's a contextual keyword: it has special meaning only in module-info.java. Code that uses module as a variable name still compiles.
Summary
- A module is a named set of packages with a
module-info.javadescriptor at its root. - The benefits are better access control, clearer dependencies, custom runtimes, security, performance and unique packages.
- Compile with
javac -p <modulepath> -d <outdir> <files>, package withjar -cvf <jar> -C <dir>/ ., and run withjava -p <modulepath> -m <module>/<class>. exportsshares a package, andrequiresdeclares a dependency on a module. A missing link causes a compile error, and a missing module causes a startup error.
Practice quiz
Test yourself with the first modular program quiz: 10 exam-style questions with explanations.
Previous: Java Resource Bundles: Properties Files, Lookup Order, MessageFormat and Properties (OCP 21)
Next: Java Module Declarations: requires, requires transitive, exports and opens (OCP 21)
Related reading
- User Authentication with JAAS in Java: Login Modules, Callbacks and Subjects
- Java Resource Bundles: Properties Files, Lookup Order, MessageFormat and Properties (OCP 21)
- Java Locales: Localizing Numbers, Currency, Percentages, Compact Numbers and Dates (OCP 21)
- Java Formatting: DecimalFormat, DateTimeFormatter Patterns and String.format (OCP 21)
- Java try-with-resources: AutoCloseable, Closing Order and Suppressed Exceptions (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.