Java Named, Automatic and Unnamed Modules: Migration Strategies (OCP 21)
Module types for the OCP 21 exam: named, automatic and unnamed modules, how automatic module names are derived from the manifest or JAR file name, what each type exports and reads, bottom-up and top-down migration, splitting a project, and cyclic dependencies.
kvi5hnuCode Sprout team member10 min readOn this page
Every module so far has had a module-info.java and lived on the module path. Real applications also depend on libraries that were never modularized, and they can't convert everything on the same day. The module system handles this with three kinds of module and two standard migration strategies. The exam asks you to compare the module types and to choose the right strategy.
Three kinds of module
Named modules
A named module has a module-info.class at its root and is placed on the module path. Its name comes from the declaration. It exports only what it declares, and it reads only the modules it requires (plus java.base). Everything in articles 73 to 76 was a named module.
Being named also matters outside this chapter. A sealed class may permit subclasses in other packages only when they're in the same named module. In the unnamed module, javac reports "class Shape in unnamed module cannot extend a sealed class in a different package".
Automatic modules
An automatic module is a plain JAR, with no module-info.class, that is placed on the module path. Java builds a module for it automatically:
- It exports and opens every package. There's no declaration to restrict anything.
- It reads every other module, including the class path. Old library code that depends on other non-modular JARs keeps working.
- It gets a name, so named modules can write
requires <name>;.
How the name is chosen
- If the JAR's
META-INF/MANIFEST.MFhas anAutomatic-Module-Nameentry, that's the name. Library authors add this to promise the name their library will use once it's properly modularized. - Otherwise the name comes from the file name:
- Remove the
.jarextension. - Remove the version at the end: a
-followed by a digit, and everything after it, such as-2.4.1,-3.0-betaor-1.0.0-SNAPSHOT. - Replace every character that isn't a letter or a digit with a dot.
- Collapse repeated dots into one.
- Remove a dot at the start or end.
- Remove the
These results all come from Java itself (jar --describe-module):
| JAR file | Automatic module name |
|---|---|
bike-rental-2.4.1.jar | bike.rental (version 2.4.1) |
json_utils-3.0-beta.jar | json.utils |
x--y..z.jar | x.y.z |
trail-map-v2.jar | trail.map.v2. v2 doesn't start with a digit, so it isn't a version. |
my.lib-1.0.0.RELEASE.jar | my.lib |
whatever-9.jar with Automatic-Module-Name: com.trails.bikes | com.trails.bikes |
class-tools-1.0.jar | none: class.tools is invalid because class is a keyword, so startup fails with FindException |
The manifest is a plain text file of Name: value lines. A JAR created by the jar tool gets a default manifest with Manifest-Version: 1.0 and Created-By: followed by the JDK version and vendor.
The unnamed module
Everything on the class path belongs to the unnamed module (each class loader has one). This is how Java worked before modules:
- It has no name, so a named module can't
requireit. Named modules can't read the class path at all. Code in a named module that uses a class-path class fails with "package helper is not visible". - It reads every module that has been resolved, and everything else on the class path.
- To other class-path code and to automatic modules, all of its packages are accessible. To named modules, it exports nothing.
- A
module-info.classin a JAR on the class path is ignored. Put a modular JAR on the class path and all its packages, even unexported ones, become accessible, so its encapsulation is lost.
One practical detail: when the main class runs from the class path, modules on the module path are only resolved if something asks for them. Add --add-modules <name> (or --add-modules ALL-MODULE-PATH) to javac and java. Otherwise, class-path code that uses them fails with "package ... is not visible" at compile time, or NoClassDefFoundError at run time.

| Question | Named | Automatic | Unnamed |
|---|---|---|---|
Contains module-info? | Yes | No | Ignored if present |
| Packages exported to named modules | Those declared | All | None |
| Packages exported to automatic modules and class path | Those declared | All | All |
| Readable by named modules? | Yes | Yes | No |
| Readable by automatic modules? | Yes | Yes | Yes |
| Readable by code on the class path? | Yes | Yes | Yes |
The key rule to remember: class-path code can use the module path, but code in named modules can't use the class path.
Migrating an application
Converting an application to modules is optional. Every Java 21 feature works on the class path. When a team does migrate, it first draws the dependency graph of its JARs, with arrows from each project to the projects it needs. Projects with no dependencies are at the bottom. The project that depends on everything else is at the top. When two projects don't depend on each other, either one can go first.
Bottom-up migration
Use it when you control all the JARs:
- Pick the lowest project that hasn't been migrated yet.
- Add a
module-info.java:exportsfor the packages higher projects use, andrequiresfor its dependencies. - Move it from the class path to the module path. It's now a named module.
- Leave every unmigrated project on the class path as part of the unnamed module.
- Repeat for the next project up.
This works because during the migration, the named modules lower down never need the class path. The unmigrated projects higher up are on the class path, and class-path code can read the module path.
Top-down migration
Use it when some JARs belong to someone else and can't be changed yet:
- Put all JARs on the module path. The unmigrated ones become automatic modules.
- Pick the highest project that hasn't been migrated.
- Add a
module-info.java, using the automatic module names of lower projects in itsrequiresdirectives. - Repeat for the next project down. Projects you don't own can stay automatic.

| Bottom-up | Top-down | |
|---|---|---|
| Starting point | All JARs on the class path | All JARs on the module path |
| Migrated first | The project with no dependencies | The project that depends on all the others |
| The project that depends on all others, while waiting | Unnamed module on the class path | Named module on the module path (already done) |
| The project with no dependencies, while waiting | Named module on the module path (already done) | Automatic module on the module path |
| Mix during migration | Named + unnamed | Named + automatic |
| Best when | You own every JAR | Other teams own some JARs |
Splitting a big project into modules
To break one large project into modules, group its packages into logical modules and draw the dependencies. Two rules from earlier articles shape the result:
- No cycles. If
tickets.pricingrequirestickets.booking, thentickets.bookingcan't requiretickets.pricing, directly or through other modules. Withball.a → ball.b → ball.c → ball.a,javacreports "cyclic dependence" for every module in the loop. The usual fix is to move the shared code into a new module that both of them require. Cycles between packages inside one module are still allowed. - No split packages. Two modules mustn't contain the same package. If a module reads both,
javacreports "module shop.c reads package shop.common from both shop.a and shop.b". Even two unexported copies fail at startup:LayerInstantiationException: Package shop.common in both module shop.a and module shop.b.
What's current
- The three module types and both strategies are unchanged since Java 9, and apply to Java 21 and 25.
- Most popular libraries have since shipped a real
module-infoor at least anAutomatic-Module-Name. Still, many applications run on the class path, and that remains fully supported. - In practice,
jdeps(article 76) is the first step of a migration:jdeps --generate-module-infocan even draft declarations for existing JARs.
Exam traps from this article
A complete example
This program reproduces the module types with real tools. It derives automatic module names for several JAR file names, including one with a manifest entry and an invalid one. It then compiles a named module that requires an automatic module, which in turn calls a helper on the class path, and runs them. It prints which module is automatic, which one exports its packages and which one can read the class path. Then it shows that a named module can't see the class path, that a modular JAR loses its encapsulation on the class path, and that split packages and a three-module cycle are rejected.
import java.io.*;
import java.lang.module.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import java.util.spi.ToolProvider;
public class Solution {
static Path root;
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; paths are relative to the temp folder.
static boolean tool(String name, String... args) {
String[] full = Arrays.stream(args)
.map(a -> a.contains("/") || a.endsWith(".jar") || a.endsWith(".txt")
? root.resolve(a).toString() : a)
.toArray(String[]::new);
var err = new StringWriter();
int code = ToolProvider.findFirst(name).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 == 0;
}
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("migrate");
try {
// A plain library class (no module-info) and a helper that stays on the class path
write("libsrc/bike/rent/Desk.java", """
package bike.rent;
public class Desk {
public static String hire() { return "bike hired, " + helper.Clock.now(); }
}
""");
write("helpsrc/helper/Clock.java", """
package helper;
public class Clock {
public static String now() { return "10:30"; }
}
""");
tool("javac", "-d", "helpout/", "helpsrc/helper/Clock.java");
tool("jar", "-cf", "cp/helper.jar", "-C", "helpout/", ".");
tool("javac", "-cp", "cp/helper.jar", "-d", "libout/", "libsrc/bike/rent/Desk.java");
System.out.println("== 1. Automatic module names derived from JAR file names");
write("manifest.txt", "Automatic-Module-Name: com.trails.bikes\n");
for (String file : List.of("bike-rental-2.4.1.jar", "json_utils-3.0-beta.jar",
"x--y..z.jar", "trail-map-v2.jar", "my.lib-1.0.0.RELEASE.jar",
"whatever-9.jar", "class-tools-1.0.jar")) {
if (file.startsWith("whatever")) {
tool("jar", "-cfm", "names/" + file, "manifest.txt", "-C", "libout/", ".");
} else {
tool("jar", "-cf", "names/" + file, "-C", "libout/", ".");
}
String result;
try {
ModuleDescriptor d = ModuleFinder.of(root.resolve("names/" + file))
.findAll().iterator().next().descriptor();
result = d.name() + d.version().map(v -> " (version " + v + ")").orElse("");
} catch (FindException e) {
result = "FindException: " + e.getCause().getMessage();
}
System.out.printf(" %-28s -> %s%n", file, result);
}
System.out.println("\n== 2. Named module app.main requires the automatic module bike.rental");
Files.createDirectories(root.resolve("mods"));
Files.copy(root.resolve("names/bike-rental-2.4.1.jar"), root.resolve("mods/bike-rental-2.4.1.jar"));
write("app/app/main/Main.java", """
package app.main;
public class Main {
public static String run() { return bike.rent.Desk.hire(); }
}
""");
write("app/module-info.java", "module app.main { requires bike.rental; }\n");
System.out.println(" compile app.main: "
+ tool("javac", "-p", "mods/", "-d", "appout/", "app/module-info.java", "app/app/main/Main.java"));
// Like: java -p mods:appout -cp cp/helper.jar -m app.main/...
ModuleFinder finder = ModuleFinder.of(root.resolve("mods"), root.resolve("appout"));
ModuleLayer boot = ModuleLayer.boot();
Configuration cf = boot.configuration().resolve(finder, ModuleFinder.of(), Set.of("app.main"));
try (var classPath = new URLClassLoader(new URL[]{root.resolve("cp/helper.jar").toUri().toURL()},
ClassLoader.getSystemClassLoader())) {
ModuleLayer.Controller ctl = ModuleLayer.defineModulesWithOneLoader(cf, List.of(boot), classPath);
ModuleLayer layer = ctl.layer();
Module app = layer.findModule("app.main").orElseThrow();
Module bike = layer.findModule("bike.rental").orElseThrow();
for (Module m : List.of(app, bike)) {
ModuleDescriptor d = m.getDescriptor();
System.out.printf(" %-12s automatic=%-5b exports its package=%-5b reads class path=%b%n",
m.getName(), d.isAutomatic(),
m.getPackages().stream().anyMatch(m::isExported),
m.canRead(classPath.getUnnamedModule()));
}
ctl.addExports(app, "app.main", Solution.class.getModule());
Object result = layer.findLoader("app.main").loadClass("app.main.Main")
.getMethod("run").invoke(null);
System.out.println(" app.main -> bike.rental -> helper on class path: " + result);
}
System.out.println("\n== 3. A named module can't see the class path");
write("app2/app/main/Main.java", """
package app.main;
public class Main { String t = helper.Clock.now(); }
""");
write("app2/module-info.java", "module app.main { }\n");
tool("javac", "-cp", "cp/helper.jar", "-d", "app2out/", "app2/module-info.java", "app2/app/main/Main.java");
System.out.println("\n== 4. A module JAR on the class path loses its encapsulation");
write("shop/shop/open/Front.java", "package shop.open;\npublic class Front { }\n");
write("shop/shop/secret/Vault.java", "package shop.secret;\npublic class Vault { public static int code() { return 4321; } }\n");
write("shop/module-info.java", "module shop { exports shop.open; }\n");
tool("javac", "-d", "shopout/", "shop/module-info.java", "shop/shop/open/Front.java", "shop/shop/secret/Vault.java");
tool("jar", "-cf", "shop.jar", "-C", "shopout/", ".");
write("user/user/User.java", "package user;\npublic class User { int c = shop.secret.Vault.code(); }\n");
System.out.println(" shop.jar on the class path: compiles=" + tool("javac", "-cp", "shop.jar", "-d", "u1/", "user/user/User.java"));
System.out.println(" shop.jar on the module path: compiles="
+ tool("javac", "-p", "shop.jar", "--add-modules", "shop", "-d", "u2/", "user/user/User.java"));
System.out.println("\n== 5. Split packages and cycles are rejected");
write("split/shop.a/shop/common/A.java", "package shop.common;\npublic class A { }\n");
write("split/shop.a/module-info.java", "module shop.a { exports shop.common; }\n");
write("split/shop.b/shop/common/B.java", "package shop.common;\npublic class B { }\n");
write("split/shop.b/module-info.java", "module shop.b { exports shop.common; }\n");
write("split/shop.c/shop/c/C.java", "package shop.c;\npublic class C { }\n");
write("split/shop.c/module-info.java", "module shop.c { requires shop.a; requires shop.b; }\n");
tool("javac", "-d", "splitout/", "--module-source-path", "split/",
"split/shop.a/shop/common/A.java", "split/shop.a/module-info.java",
"split/shop.b/shop/common/B.java", "split/shop.b/module-info.java",
"split/shop.c/shop/c/C.java", "split/shop.c/module-info.java");
write("cycle/ball.a/module-info.java", "module ball.a { requires ball.b; }\n");
write("cycle/ball.b/module-info.java", "module ball.b { requires ball.c; }\n");
write("cycle/ball.c/module-info.java", "module ball.c { requires ball.a; }\n");
tool("javac", "-d", "cycleout/", "--module-source-path", "cycle/",
"cycle/ball.a/module-info.java", "cycle/ball.b/module-info.java", "cycle/ball.c/module-info.java");
} finally {
deleteTree(root);
}
}
}
Output:
== 1. Automatic module names derived from JAR file names
bike-rental-2.4.1.jar -> bike.rental (version 2.4.1)
json_utils-3.0-beta.jar -> json.utils (version 3.0-beta)
x--y..z.jar -> x.y.z
trail-map-v2.jar -> trail.map.v2
my.lib-1.0.0.RELEASE.jar -> my.lib (version 1.0.0.RELEASE)
whatever-9.jar -> com.trails.bikes (version 9)
class-tools-1.0.jar -> FindException: class.tools: Invalid module name: 'class' is not a Java identifier
== 2. Named module app.main requires the automatic module bike.rental
compile app.main: true
app.main automatic=false exports its package=false reads class path=false
bike.rental automatic=true exports its package=true reads class path=true
app.main -> bike.rental -> helper on class path: bike hired, 10:30
== 3. A named module can't see the class path
error: package helper is not visible
== 4. A module JAR on the class path loses its encapsulation
shop.jar on the class path: compiles=true
error: package shop.secret is not visible
shop.jar on the module path: compiles=false
== 5. Split packages and cycles are rejected
error: module shop.c reads package shop.common from both shop.a and shop.b
error: cyclic dependence involving ball.c
error: cyclic dependence involving ball.b
error: cyclic dependence involving ball.a
Points to notice:
json_utils-3.0-beta.jarlost the version3.0-beta, and its_became a dot.trail-map-v2keptv2, because a version must start with a digit.- The manifest name
com.trails.bikeswon over the file name. The version 9 still came from the file name. - The automatic module
bike.rentalexports its package and reads the class path, so its call tohelper.Clockworked. The named moduleapp.maindoes neither. - Compiling
app.mainwith only-cp cp/helper.jarfailed: named modules never see the class path. shop.secretisn't exported, yet it compiled whenshop.jarwas on the class path. On the module path, the same code was rejected.
Common questions
Can a JAR be named on one run and unnamed on the next? Yes. It depends only on where you put it. A modular JAR on the class path is part of the unnamed module, and on the module path it's a named module.
Can a named module require an automatic module? Yes, by its automatic name. That's exactly how top-down migration works. The reverse is also true: automatic modules read all named modules.
Why can't named modules read the class path? Reliable configuration. A named module's dependencies must all be declared and checked at startup, and the class path has no names to declare.
Does every project have to be migrated? No. Libraries can stay automatic modules or on the class path indefinitely.
Summary
- Named modules have
module-infoand live on the module path. Automatic modules are plain JARs on the module path, named from the manifest or the file name. The unnamed module is the class path. - Automatic modules export everything and read everything. The unnamed module reads everything but exports nothing to named modules. Named modules read only what they require, and never the class path.
- Bottom-up migration converts from the lowest project up, with unmigrated code on the class path. Top-down migration puts everything on the module path and converts from the top down.
- Module graphs must not have cycles or split packages. Break a cycle by extracting shared code into a new module.
Practice quiz
Test yourself with the module types and migration quiz: 10 exam-style questions with explanations.
You've finished Chapter 12. Check your understanding of the whole chapter with the Chapter 12 review quiz: 20 mixed questions on module declarations, commands, services, module types and migration.
Previous: Java Module Commands: describe-module, jdeps, jmod and jlink (OCP 21)
Next: Java Threads: Platform and Virtual Threads, Thread States and Interrupting (OCP 21)
Related reading
- Java Module Commands: describe-module, jdeps, jmod and jlink (OCP 21)
- Java Module Services: Service Provider Interface, ServiceLoader, uses and provides (OCP 21)
- Java Module Declarations: requires, requires transitive, exports and opens (OCP 21)
- Java Modules: Benefits, module-info.java, Compiling, Running and Packaging (OCP 21)
- User Authentication with JAAS in Java: Login Modules, Callbacks and Subjects

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.