Java Modules Introduction: The Module Concept and a Hello World Module
Get started with the Java Platform Module System (JPMS): why modules exist, strong encapsulation and reliable configuration, how to name modules, write module-info.java, compile a modular Hello World and run it with --module-path and --module.
kvi5hnuCode Sprout team member9 min readOn this page
Encapsulation is at the heart of object-oriented programming. A class has a public interface and a private implementation, and the implementation can change without breaking users. A module system brings the same benefit to programming in the large. A module decides which of its packages others may use, so its evolution stays under control. Java 9 introduced the Java Platform Module System (JPMS), which is built into the compiler and the virtual machine. It modularized the JDK itself, and you can use it for your own code. Even if you never write a module, the modularized platform affects you, as later articles show.
Why modules?
Classes encapsulate with private. Packages add a second level: members with package access (no modifier) are visible only inside the package. In large systems that isn't enough, because anything public is accessible from everywhere. Once a class is public, you can't tell who depends on it, so you can't safely change or remove it.
The JDK designers faced exactly this problem. After twenty years, the JDK had become a giant tangle with some clearly obsolete parts. CORBA (org.omg.CORBA) shipped with every JDK until Java 10 and was finally dropped in Java 11. Meanwhile, seemingly unrelated parts were secretly connected. The SOAP web services code used java.awt.datatransfer.DataFlavor, so a server application couldn't simply leave out the desktop classes. Existing module systems such as OSGi didn't fit the JDK's needs, so a new system was designed and made part of the Java language and the JVM.
A Java platform module consists of
- a collection of packages
- optionally, resource files and other files such as native libraries
- a list of the packages in the module that are accessible to others
- a list of all modules this module depends on
The platform enforces this encapsulation and these dependencies both at compile time and in the virtual machine.

Compared with plain JAR files on the class path, modules offer two main advantages:
- Strong encapsulation. You decide which packages are accessible. You don't have to maintain code that you never meant to be public, even if it contains
publicclasses. - Reliable configuration. Common class path problems, such as a missing JAR discovered only when a class is first needed, or two JARs containing the same package, are detected at startup.
There are a few things JPMS deliberately doesn't do. It has no versioning. You can't say which version of a module you require, and you can't use two versions of a module in one program. Build tools such as Maven and Gradle handle versions. Other systems, such as OSGi or separate class loaders, support multiple versions at runtime.
Naming modules
A module is a collection of packages, and the package names don't need to be related. The java.sql module contains the packages java.sql and javax.sql. (Its XA support lives in a separate module, java.transaction.xa, which java.sql requires transitively.) As this example shows, a module may also have the same name as one of its packages.
Module names follow the same rules as package names: letters, digits, underscores and periods. As with packages, there is no hierarchy. com.example and com.example.util are completely unrelated modules.
For modules meant to be used by others, the name must be globally unique. The convention is reverse domain names, and the easiest approach is to name the module after its top-level package. The SLF4J logging facade, for example, is the module org.slf4j, with packages org.slf4j, org.slf4j.spi, org.slf4j.event and org.slf4j.helpers. This also prevents package conflicts: a package may belong to only one module, so if module names are unique and package names start with the module name, the package names are unique too.
Shorter names are fine for modules nobody else will use, such as the module containing your application. This part uses short names like hellomod for programs and reverse domain names like com.example.util for library-like modules.
Module names appear only in module declarations and on the command line. In your Java source files, you keep using package names in import statements exactly as before.
A modular "Hello, World!"
First, the class must be in a package. The unnamed package can't be part of a module:
package com.example.hello;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Modular World!");
}
}
So far nothing is new. To turn this into a module named hellomod, add a module declaration in a file called module-info.java, placed in the module's base directory, which is the directory containing com. By convention, the base directory has the same name as the module:
hellomod/
├── module-info.java
└── com/
└── example/
└── hello/
└── HelloWorld.java
The declaration is empty, because this module offers nothing to anyone and needs nothing beyond the always-present java.base:
module hellomod {
}
Compile as usual:
javac hellomod/module-info.java hellomod/com/example/hello/HelloWorld.java
module-info.java doesn't look like an ordinary Java source file, and it can't contain a class, because class names can't contain a hyphen. module, requires, exports and the other words used in it are restricted keywords (contextual keywords). They have a special meaning only inside a module declaration, so you can still use them as variable names elsewhere. The file compiles to module-info.class, which holds the module definition in binary form.
To run the program as a modular application, give the module path, which is like the class path but contains modules, and name the main class as modulename/classname:
java --module-path hellomod --module hellomod/com.example.hello.HelloWorld
or, with the short options -p and -m:
java -p hellomod -m hellomod/com.example.hello.HelloWorld
Either way, "Hello, Modular World!" appears, and you've modularized your first application.
A complete example
The demo first looks at the running program. Because Solution is launched from the class path, it lives in the unnamed module, while String is in java.base and java.sql.Connection in java.sql. It then writes the Hello World module to a temporary directory and compiles it with javac, run in-process through java.util.spi.ToolProvider. It runs the module with both forms of the java command and reads back what module-info.class records. It also triggers the terminal-digits warning, and shows that a class in the unnamed package is rejected when the module is resolved.
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 a source file below root/src. */
static void source(String path, String text) throws IOException {
Path p = root.resolve("src").resolve(path);
Files.createDirectories(p.getParent());
Files.writeString(p, text);
}
/** Runs a JDK tool such as javac in-process and returns its output lines. */
static List<String> tool(String name, String... args) {
var out = new StringWriter();
int rc = ToolProvider.findFirst(name).orElseThrow()
.run(new PrintWriter(out, true), new PrintWriter(out, true), args);
var lines = new ArrayList<>(out.toString().lines().map(l -> l.replace(root.toString(), "")).toList());
if (rc != 0) lines.add(name + " exit code " + rc);
return lines;
}
/** Runs "java <args>" in a child process and prints its output, like typing the command. */
static void java(String... args) throws IOException, InterruptedException {
var cmd = new ArrayList<String>();
cmd.add(Path.of(System.getProperty("java.home"), "bin", "java").toString());
cmd.addAll(List.of(args));
System.out.println(" $ java " + String.join(" ", args).replace(root.toString() + File.separator, ""));
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
new String(p.getInputStream().readAllBytes()).lines().forEach(l -> System.out.println(" " + l));
p.waitFor();
}
public static void main(String[] args) throws Exception {
root = Files.createTempDirectory("mods");
System.out.println("-- modules of the running program --");
System.out.println(" Solution is in a named module: " + Solution.class.getModule().isNamed() + " (class path = unnamed module)");
System.out.println(" String is in module: " + String.class.getModule().getName());
System.out.println(" java.sql.Connection is in module: " + java.sql.Connection.class.getModule().getName());
ModuleDescriptor sql = ModuleLayer.boot().findModule("java.sql").orElseThrow().getDescriptor();
System.out.println(" java.sql contains packages: " + new TreeSet<>(sql.packages()));
System.out.println(" java.sql requires java.base: "
+ sql.requires().stream().anyMatch(r -> r.name().equals("java.base")));
System.out.println("-- a modular Hello World --");
source("hellomod/module-info.java", """
module hellomod {
}
""");
source("hellomod/com/example/hello/HelloWorld.java", """
package com.example.hello;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Modular World!");
System.out.println("running in module: " + HelloWorld.class.getModule().getName());
}
}
""");
Path out = root.resolve("out/hellomod");
System.out.println(" javac output: " + tool("javac", "-d", out.toString(),
root.resolve("src/hellomod/module-info.java").toString(),
root.resolve("src/hellomod/com/example/hello/HelloWorld.java").toString()));
System.out.println(" compiled files: " + listFiles(out));
java("--module-path", root.resolve("out").toString(), "--module", "hellomod/com.example.hello.HelloWorld");
java("-p", root.resolve("out").toString(), "-m", "hellomod/com.example.hello.HelloWorld");
System.out.println("-- what module-info.class contains --");
ModuleDescriptor d = ModuleFinder.of(root.resolve("out")).find("hellomod").orElseThrow().descriptor();
System.out.println(" name: " + d.name() + ", packages: " + d.packages() + ", exports: " + d.exports()
+ ", requires: " + d.requires().stream().map(ModuleDescriptor.Requires::name).toList());
System.out.println("-- module names that end in digits get a warning --");
source("app.v2/module-info.java", "module app.v2 { }\n");
source("app.v2/com/example/app/App.java", "package com.example.app; public class App { }\n");
tool("javac", "-Xlint:module", "-d", root.resolve("out2/app.v2").toString(),
root.resolve("src/app.v2/module-info.java").toString(),
root.resolve("src/app.v2/com/example/app/App.java").toString())
.stream().filter(l -> l.contains("warning:")).forEach(l -> System.out.println(" " + l.substring(l.indexOf("warning:"))));
System.out.println("-- a class in the unnamed package cannot be in a module --");
source("broken/module-info.java", "module broken { }\n");
source("broken/Hello.java", "public class Hello { }\n");
System.out.println(" javac output: " + tool("javac", "-d", root.resolve("out3/broken").toString(),
root.resolve("src/broken/module-info.java").toString(),
root.resolve("src/broken/Hello.java").toString()));
try {
ModuleFinder.of(root.resolve("out3")).find("broken");
} catch (FindException e) {
Throwable cause = e.getCause() != null ? e.getCause() : e;
System.out.println(" module system: " + cause.getMessage().replace(root.toString(), ""));
}
try (var walk = Files.walk(root)) { walk.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete()); }
}
static List<String> listFiles(Path dir) throws IOException {
try (var s = Files.walk(dir)) {
return s.filter(Files::isRegularFile).map(p -> dir.relativize(p).toString().replace(File.separatorChar, '/')).sorted().toList();
}
}
}
-- modules of the running program --
Solution is in a named module: false (class path = unnamed module)
String is in module: java.base
java.sql.Connection is in module: java.sql
java.sql contains packages: [java.sql, javax.sql]
java.sql requires java.base: true
-- a modular Hello World --
javac output: []
compiled files: [com/example/hello/HelloWorld.class, module-info.class]
$ java --module-path out --module hellomod/com.example.hello.HelloWorld
Hello, Modular World!
running in module: hellomod
$ java -p out -m hellomod/com.example.hello.HelloWorld
Hello, Modular World!
running in module: hellomod
-- what module-info.class contains --
name: hellomod, packages: [com.example.hello], exports: [], requires: [java.base]
-- module names that end in digits get a warning --
warning: [module] module name component v2 should avoid terminal digits
-- a class in the unnamed package cannot be in a module --
javac output: []
module system: Hello.class found in top-level directory (unnamed package not allowed in module)
Common questions
Do I have to use modules?
No. Code on the class path still works and runs in the unnamed module. Many applications never write a module-info.java. Modules pay off most for libraries that want to hide their internals and for applications that use jlink to build a small runtime.
Can a module contain classes in the default (unnamed) package? No. Every class in a module must be in a named package. Move the classes into a package first.
Are module and requires reserved words now?
No. They're contextual keywords that only have a special meaning inside module-info.java. You can still use them as variable, method or package names elsewhere.
Can I require a particular version of a module? No. JPMS has no version selection, and a program can contain only one module with a given name. Build tools such as Maven and Gradle choose the versions, and the module system checks the result at startup.
What is the difference between the class path and the module path?
JARs on the class path go into the unnamed module, without encapsulation or dependency checks. JARs on the module path become named modules, explicit or automatic, and the JVM checks their dependencies and enforces their exports before main runs.
API reference
java.lang.Module, java.lang.module and tools
| Method / option | Description |
|---|---|
Module Class.getModule() | the module containing a class (the unnamed module for class-path code) |
String Module.getName(), boolean isNamed(), ModuleDescriptor getDescriptor() | module identity and declaration |
Optional<Module> ModuleLayer.boot().findModule(String name) | a module of the boot layer (the JDK and your module path) |
ModuleDescriptor.name(), packages(), requires(), exports() | the contents of module-info.class |
static ModuleFinder ModuleFinder.of(Path... paths) | finds modules in directories or JARs, like --module-path |
static Optional<ToolProvider> ToolProvider.findFirst(String name) | runs javac, jar, jlink, jdeps… in-process |
java --module-path (-p), --module (-m) module/mainclass | run a modular application |
Summary
- JPMS adds a third level of encapsulation above classes and packages. A module bundles packages and resources, declares which packages it exports and which modules it requires, and is enforced by
javacand the JVM. - The benefits are strong encapsulation (unexported packages are hidden, even their public classes) and reliable configuration. Versioning is out of scope.
- Module names are globally unique, conventionally the top-level package name, and not hierarchical. Source files still use package names only.
module-info.javain the module's base directory declares the module, and classes must be in named packages. Run modules withjava -p modulepath -m module/mainclass.
Practice Questions
What two main benefits does the module system offer over JAR files on the class path?
Strong encapsulation and reliable configuration. A module controls which packages other code may use, even if their classes are public. The module system also checks at startup that all required modules are present and that no package appears in two modules.
Are the modules com.example and com.example.util related?
No. Module names have no hierarchy, so they're two unrelated modules, just as packages with similar names are unrelated.
Why can't HelloWorld stay in the unnamed (default) package when you put it into a module?
Every class in a module must belong to a named package, because the module system works at the level of packages, which it exports, opens and checks for conflicts. When the module is resolved, a class in the unnamed package is rejected.
How do you run the main class com.example.hello.HelloWorld of the module hellomod located in the directory mods?
Use java --module-path mods --module hellomod/com.example.hello.HelloWorld, or the short form java -p mods -m hellomod/com.example.hello.HelloWorld.
Can you still name a variable "module" or "exports" in ordinary code?
Yes. module, requires, exports and the other module words are restricted (contextual) keywords that are special only inside module-info.java.
Previous: Java Bytecode Engineering: Modifying Class Files with ASM and Java Agents
Next: Java Module requires and exports: Dependencies and Exported Packages
Related reading
- Java Bytecode Engineering: Modifying Class Files with ASM and Java Agents
- Java char, Unicode and boolean: Characters, Escape Sequences and Truth Values
- Java Annotation Processors: Generating Source Code at Compile Time
- Processing Java Annotations at Runtime with Reflection
- Java Built-in Annotations: @Override, @Deprecated, @SuppressWarnings and Meta-Annotations

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.