Java Modules: Introduction to the Java Module System

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 229 of 306

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 classpathHow Java modules fix it
A missing JAR is only noticed when a class is first used, possibly hours after startupReliable 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 internalStrong 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 itScalable runtime: jlink builds a runtime containing only the modules an app needs

Three terms appear throughout this lesson:

TermMeaning
ModuleA named set of packages plus a descriptor, module-info.java
Module pathLike the classpath, but for modules (--module-path or -p)
Unnamed moduleWhere 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.base holds the core packages: java.lang, java.util, java.io, java.time and more. Every module reads it automatically, which is what mandated means.
  • java.sql exports 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 src tells javac that each folder under src is one module.
  • -m com.gocourse.hello compiles that module and anything it needs.
  • The compiled module gets its own folder under out, and module-info.java becomes module-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 the Module object a class belongs to. String belongs to java.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.pricing says the store module reads the pricing module.
  • exports com.gocourse.pricing.api makes that one package accessible to modules that read pricing.
  • PriceCalculator can still use TaxTable, because both are inside the same module. Encapsulation only applies between modules.
  • Headphones cost 1999.0 × 1.18 = 2358.82; tea costs 250.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 public and in an exported package to be used from another module.
  • The pricing team can now change or delete TaxTable without 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.

ErrorCauseFix
package X is not visible ... which does not export itPackage not exported by its moduleAdd exports X; to that module, or use its public API instead
package X is not visible ... does not read itMissing requiresAdd requires othermodule; to your module-info.java
FindException: Module X not foundModule JAR or folder not on the module pathAdd 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-class stores the main class in the module descriptor, so -m com.gocourse.store is enough.
  • -p mods points at a folder of JARs; the JVM reads each one's module-info.class to find modules by name.
  • jar --describe-module on pricing.jar would show exports com.gocourse.pricing.api and contains 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

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.store starts from the store module and adds everything it requires: pricing and java.base. Nothing else from the JDK is included.
  • --launcher store=com.gocourse.store creates a bin/store script that starts the app.
  • The store-runtime folder 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-debug shrink it further.

Note: jlink only works when every module, including libraries, is a real named module. Most modern Java libraries ship with a module-info.class or an Automatic-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:

  1. One job per module. model holds data, service holds logic and storage, and app only wires them together. The module graph is app → service → model, plus app → model.
  2. A JDK module. java.util.logging is in the java.logging module, not in java.base, so the service module must requires java.logging. Without it, compiling LibraryService fails with "package java.util.logging is not visible".
  3. Hidden storage. BookStore is public so LibraryService can use it across packages, but service.internal is not exported. The app module cannot touch the book list directly; it must go through LibraryService.
  4. App requires model too. LibraryApp uses Book directly, so it needs requires com.gocourse.library.model. The next lesson shows how requires transitive in the service module removes this extra line.
  5. The run. Two books start available. Borrowing 978-01 succeeds; 978-02 was already out, so the service logs a warning. Only Clean Java Code remains available.
  6. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Modules: Introduction to the Java Module System and get answers drawn from it.

Signed-in readers only.