Java Modules: Introduction to the Java Module System
Java modules group related packages into a named unit that declares which other modules it needs and which of its packages other code may use. The Java Platform Module System (JPMS), added in Java 9, uses that information to check dependencies when your program starts and to hide internal packages, even ones that contain public classes.
In this lesson you will explore the modules inside the JDK, build and run your first module, connect two modules with requires and exports, see the errors the module system reports, package modules as modular JARs, and create a small custom Java runtime with jlink. The next lesson, module-info in Java, covers every directive of the module descriptor in depth.
Why Java Modules Exist
Before Java 9, every JAR went on one flat classpath. That caused two problems that modules solve:
| Problem on the classpath | How Java modules fix it |
|---|---|
| A missing JAR is only noticed when a class is first used, possibly hours after startup | Reliable configuration: every requires is checked at startup, and the JVM refuses to start if a module is missing |
Every public class is usable by everyone, including classes meant to be internal | Strong encapsulation: only packages listed in exports are accessible to other modules |
| The whole JDK is always shipped, even if an app uses a small part of it | Scalable runtime: jlink builds a runtime containing only the modules an app needs |
Three terms appear throughout this lesson:
| Term | Meaning |
|---|---|
| Module | A named set of packages plus a descriptor, module-info.java |
| Module path | Like the classpath, but for modules (--module-path or -p) |
| Unnamed module | Where code on the classpath lives; it can read every module |
Note: Modules are optional. Every program from earlier lessons ran on the classpath and still works the same way on the newest JDK. Modules matter most for libraries, larger applications and small custom runtimes.
Exploring the Modules in the JDK
The JDK itself is split into modules. List them with java --list-modules:
java --list-modules
Output (first lines, JDK 21):
java.base@21.0.12.1
java.compiler@21.0.12.1
java.datatransfer@21.0.12.1
java.desktop@21.0.12.1
java.instrument@21.0.12.1
java.logging@21.0.12.1
java.management@21.0.12.1
java.management.rmi@21.0.12.1
Look inside one module with --describe-module:
java --describe-module java.sql
Output:
java.sql@21.0.12.1
exports java.sql
exports javax.sql
requires java.base mandated
requires java.transaction.xa transitive
requires java.logging transitive
requires java.xml transitive
uses java.sql.Driver
How it works:
- The full JDK has around 70 modules. The version after
@matches your JDK, so your numbers may differ. java.baseholds the core packages:java.lang,java.util,java.io,java.timeand more. Every module reads it automatically, which is whatmandatedmeans.java.sqlexports two packages and needs three other modules. The JDBC code from earlier lessons lives here.
Creating Your First Java Module
A module is a source folder that contains a module-info.java file next to its package folders. The folder is usually named after the module.
hello/src/
└── com.gocourse.hello/ module folder
├── module-info.java module descriptor
└── com/gocourse/hello/Main.java package com.gocourse.hello
src/com.gocourse.hello/module-info.java:
module com.gocourse.hello {
}
src/com.gocourse.hello/com/gocourse/hello/Main.java:
package com.gocourse.hello;
public class Main {
public static void main(String[] args) {
Module module = Main.class.getModule();
System.out.println("Hello from module " + module.getName());
System.out.println("Named module? " + module.isNamed());
System.out.println("String lives in " + String.class.getModule().getName());
}
}
Compiling a Module
Run javac from the hello folder with --module-source-path:
javac -d out --module-source-path src -m com.gocourse.hello
find out -type f | sort
Output:
out/com.gocourse.hello/com/gocourse/hello/Main.class
out/com.gocourse.hello/module-info.class
How it works:
--module-source-path srctellsjavacthat each folder undersrcis one module.-m com.gocourse.hellocompiles that module and anything it needs.- The compiled module gets its own folder under
out, andmodule-info.javabecomesmodule-info.class. - Module names follow the same reverse-domain style as package names. Using your main package name as the module name is the usual choice.
Running a Module
java --module-path out --module com.gocourse.hello/com.gocourse.hello.Main
Output:
Hello from module com.gocourse.hello
Named module? true
String lives in java.base
How it works:
--module-path out(short form-p out) tells the JVM where to find modules.--module module/class(short form-m) names the module and the main class inside it.getModule()returns theModuleobject a class belongs to.Stringbelongs tojava.base.
The same class files can still run on the classpath:
java -cp out/com.gocourse.hello com.gocourse.hello.Main
Output:
Hello from module null
Named module? false
String lives in java.base
On the classpath, module-info.class is ignored and the class lands in the unnamed module, which has no name.
Connecting Modules With requires and exports
Real programs have several modules. Here a pricing module calculates prices, and a store module uses it. The pricing module has a public API package and an internal package it wants to keep private.
shop/src/
├── com.gocourse.pricing/
│ ├── module-info.java
│ └── com/gocourse/pricing/
│ ├── api/PriceCalculator.java
│ └── internal/TaxTable.java
└── com.gocourse.store/
├── module-info.java
└── com/gocourse/store/StoreApp.java
com.gocourse.pricing/module-info.java:
module com.gocourse.pricing {
exports com.gocourse.pricing.api; // only this package is visible to other modules
}
api/PriceCalculator.java:
package com.gocourse.pricing.api;
import com.gocourse.pricing.internal.TaxTable;
public final class PriceCalculator {
private PriceCalculator() { }
public static double finalPrice(String category, double basePrice) {
double rate = TaxTable.rateFor(category);
return Math.round(basePrice * (1 + rate) * 100) / 100.0;
}
}
internal/TaxTable.java:
package com.gocourse.pricing.internal;
import java.util.Map;
public final class TaxTable {
private static final Map<String, Double> RATES = Map.of(
"books", 0.0,
"food", 0.05,
"electronics", 0.18);
private TaxTable() { }
public static double rateFor(String category) {
return RATES.getOrDefault(category, 0.12);
}
}
com.gocourse.store/module-info.java:
module com.gocourse.store {
requires com.gocourse.pricing; // read the pricing module
}
com/gocourse/store/StoreApp.java:
package com.gocourse.store;
import com.gocourse.pricing.api.PriceCalculator;
public class StoreApp {
public static void main(String[] args) {
System.out.println("Java book: " + PriceCalculator.finalPrice("books", 499.0));
System.out.println("Headphones: " + PriceCalculator.finalPrice("electronics", 1999.0));
System.out.println("Tea pack: " + PriceCalculator.finalPrice("food", 250.0));
System.out.println("Calculator module: " + PriceCalculator.class.getModule().getName());
}
}
Compile all modules at once and run:
javac -d out --module-source-path src $(find src -name "*.java")
java -p out -m com.gocourse.store/com.gocourse.store.StoreApp
Output:
Java book: 499.0
Headphones: 2358.82
Tea pack: 262.5
Calculator module: com.gocourse.pricing
How it works:
requires com.gocourse.pricingsays the store module reads the pricing module.exports com.gocourse.pricing.apimakes that one package accessible to modules that read pricing.PriceCalculatorcan still useTaxTable, because both are inside the same module. Encapsulation only applies between modules.- Headphones cost
1999.0 × 1.18 = 2358.82; tea costs250.0 × 1.05 = 262.5; books have 0% tax.
Strong Encapsulation: When public Is Not Enough
TaxTable is a public class with a public method. On the classpath any code could call it. Inside a module, it is hidden because its package is not exported. Add this class to the store module:
package com.gocourse.store;
import com.gocourse.pricing.internal.TaxTable;
public class Sneaky {
public static void main(String[] args) {
System.out.println(TaxTable.rateFor("books"));
}
}
Output (compile error):
src/com.gocourse.store/com/gocourse/store/Sneaky.java:3: error: package com.gocourse.pricing.internal is not visible
import com.gocourse.pricing.internal.TaxTable;
^
(package com.gocourse.pricing.internal is declared in module com.gocourse.pricing, which does not export it)
1 error
How it works:
- The compiler explains exactly why: the package exists, but its module does not export it.
- This is a new layer on top of the rules in Access Control in Java. A class must be
publicand in an exported package to be used from another module. - The pricing team can now change or delete
TaxTablewithout breaking any other module.
Forgetting requires
If the store module removes requires com.gocourse.pricing;, even the exported package becomes unreadable:
src/com.gocourse.store/com/gocourse/store/StoreApp.java:3: error: package com.gocourse.pricing.api is not visible
import com.gocourse.pricing.api.PriceCalculator;
^
(package com.gocourse.pricing.api is declared in module com.gocourse.pricing, but module com.gocourse.store does not read it)
1 error
A Missing Module at Startup
If the store module is on the module path but the pricing module is not, the JVM stops before running a single line of your code:
Error occurred during initialization of boot layer
java.lang.module.FindException: Module com.gocourse.pricing not found, required by com.gocourse.store
This is reliable configuration. On the classpath, the same mistake shows up later as a NoClassDefFoundError, as you saw in JAR File in Java.
| Error | Cause | Fix |
|---|---|---|
package X is not visible ... which does not export it | Package not exported by its module | Add exports X; to that module, or use its public API instead |
package X is not visible ... does not read it | Missing requires | Add requires othermodule; to your module-info.java |
FindException: Module X not found | Module JAR or folder not on the module path | Add it to --module-path |
Packaging Modules as Modular JARs
A modular JAR is a normal JAR with module-info.class at its root. Create one per module:
mkdir -p mods
jar --create --file mods/pricing.jar -C out/com.gocourse.pricing .
jar --create --file mods/store.jar --main-class com.gocourse.store.StoreApp -C out/com.gocourse.store .
jar --describe-module --file mods/store.jar
Output (first line shortened):
com.gocourse.store jar:file:///.../mods/store.jar!/module-info.class
requires com.gocourse.pricing
requires java.base mandated
contains com.gocourse.store
main-class com.gocourse.store.StoreApp
Run by module name only:
java -p mods -m com.gocourse.store
Output:
Java book: 499.0
Headphones: 2358.82
Tea pack: 262.5
Calculator module: com.gocourse.pricing
How it works:
--main-classstores the main class in the module descriptor, so-m com.gocourse.storeis enough.-p modspoints at a folder of JARs; the JVM reads each one'smodule-info.classto find modules by name.jar --describe-moduleonpricing.jarwould showexports com.gocourse.pricing.apiandcontains com.gocourse.pricing.internal. "Contains" means the package is present but hidden.
To see the dependency graph, use jdeps:
jdeps --module-path mods -s mods/store.jar mods/pricing.jar
Output:
com.gocourse.pricing -> java.base
com.gocourse.store -> com.gocourse.pricing
com.gocourse.store -> java.base
Building a Custom Runtime With jlink
Because modules declare their dependencies, jlink can build a Java runtime that contains only the modules your app needs.
jlink --module-path mods --add-modules com.gocourse.store \
--launcher store=com.gocourse.store --output store-runtime
./store-runtime/bin/java --list-modules
./store-runtime/bin/store
Output:
com.gocourse.pricing
com.gocourse.store
java.base@21.0.12.1
Java book: 499.0
Headphones: 2358.82
Tea pack: 262.5
Calculator module: com.gocourse.pricing
How it works:
--add-modules com.gocourse.storestarts from the store module and adds everything it requires: pricing andjava.base. Nothing else from the JDK is included.--launcher store=com.gocourse.storecreates abin/storescript that starts the app.- The
store-runtimefolder runs on a machine with no Java installed (same operating system and CPU type). It is much smaller than a full JDK, and options such as--strip-debugshrink it further.
Note:
jlinkonly works when every module, including libraries, is a real named module. Most modern Java libraries ship with amodule-info.classor anAutomatic-Module-Name.
Real-World Example: A Three-Module Library App
This app splits a small library system into three modules, uses a JDK module besides java.base, and hides an internal storage package.
lib/src/
├── com.gocourse.library.model/ exports model (the Book record)
├── com.gocourse.library.service/ exports service, hides service.internal
└── com.gocourse.library.app/ the entry point
com.gocourse.library.model/module-info.java and Book.java:
module com.gocourse.library.model {
exports com.gocourse.library.model;
}
package com.gocourse.library.model;
public record Book(String isbn, String title, String author, boolean available) { }
com.gocourse.library.service/module-info.java:
module com.gocourse.library.service {
requires com.gocourse.library.model;
requires java.logging; // a JDK module, not in java.base
exports com.gocourse.library.service; // internal stays hidden
}
service/internal/BookStore.java:
package com.gocourse.library.service.internal;
import com.gocourse.library.model.Book;
import java.util.ArrayList;
import java.util.List;
public class BookStore {
private final List<Book> books = new ArrayList<>(List.of(
new Book("978-01", "Learning Java", "Asha Kumar", true),
new Book("978-02", "Java Modules in Practice", "Ravi Shankar", false),
new Book("978-03", "Clean Java Code", "Asha Kumar", true)));
public List<Book> all() {
return List.copyOf(books);
}
public void replace(Book oldBook, Book newBook) {
books.set(books.indexOf(oldBook), newBook);
}
}
service/LibraryService.java:
package com.gocourse.library.service;
import com.gocourse.library.model.Book;
import com.gocourse.library.service.internal.BookStore;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;
public class LibraryService {
private static final Logger LOG = Logger.getLogger(LibraryService.class.getName());
private final BookStore store = new BookStore();
public List<Book> availableBooks() {
return store.all().stream().filter(Book::available).toList();
}
public Optional<Book> borrow(String isbn) {
Optional<Book> match = store.all().stream()
.filter(book -> book.isbn().equals(isbn) && book.available())
.findFirst();
if (match.isEmpty()) {
LOG.warning("Cannot borrow " + isbn);
return match;
}
Book book = match.get();
store.replace(book, new Book(book.isbn(), book.title(), book.author(), false));
return match;
}
}
com.gocourse.library.app/module-info.java and LibraryApp.java:
module com.gocourse.library.app {
requires com.gocourse.library.service;
requires com.gocourse.library.model;
}
package com.gocourse.library.app;
import com.gocourse.library.model.Book;
import com.gocourse.library.service.LibraryService;
public class LibraryApp {
public static void main(String[] args) {
LibraryService service = new LibraryService();
System.out.println("Available: " + service.availableBooks().stream().map(Book::title).toList());
service.borrow("978-01").ifPresent(book -> System.out.println("Borrowed: " + book.title()));
service.borrow("978-02"); // already out: logs a warning
System.out.println("Available: " + service.availableBooks().stream().map(Book::title).toList());
for (Class<?> type : new Class<?>[]{LibraryApp.class, LibraryService.class, Book.class}) {
System.out.printf("%-15s -> %s%n", type.getSimpleName(), type.getModule().getName());
}
}
}
Compile, package as modular JARs and run from the lib folder:
javac -d out --module-source-path src $(find src -name "*.java")
mkdir -p mods
jar --create --file mods/library-model.jar -C out/com.gocourse.library.model .
jar --create --file mods/library-service.jar -C out/com.gocourse.library.service .
jar --create --file mods/library-app.jar --main-class com.gocourse.library.app.LibraryApp \
-C out/com.gocourse.library.app .
java -p mods -m com.gocourse.library.app
Output (the two log lines go to standard error and show your current date and time):
Available: [Learning Java, Clean Java Code]
Borrowed: Learning Java
Nov 17, 2026 3:50:04 PM com.gocourse.library.service.LibraryService borrow
WARNING: Cannot borrow 978-02
Available: [Clean Java Code]
LibraryApp -> com.gocourse.library.app
LibraryService -> com.gocourse.library.service
Book -> com.gocourse.library.model
How it works:
- One job per module.
modelholds data,serviceholds logic and storage, andapponly wires them together. The module graph isapp → service → model, plusapp → model. - A JDK module.
java.util.loggingis in thejava.loggingmodule, not injava.base, so the service module mustrequires java.logging. Without it, compilingLibraryServicefails with "package java.util.logging is not visible". - Hidden storage.
BookStoreispublicsoLibraryServicecan use it across packages, butservice.internalis not exported. The app module cannot touch the book list directly; it must go throughLibraryService. - App requires model too.
LibraryAppusesBookdirectly, so it needsrequires com.gocourse.library.model. The next lesson shows howrequires transitivein the service module removes this extra line. - The run. Two books start available. Borrowing
978-01succeeds;978-02was already out, so the service logs a warning. Only Clean Java Code remains available. - Module names at runtime.
getModule().getName()confirms each class runs in its own named module.
For a recap of how the classes inside these modules are organized into packages, see Package in Java.