All 15 Java Platform Module System (JPMS) questions
More in Java Platform Module System (JPMS)
Advertisement
Java › Java Platform Module System (JPMS)

How would you write and run a basic 'Hello World' JPMS-modularized application from scratch, including the module-info.java, directory structure, and the specific javac/java command-line invocations needed?

Intermediate

Answer

A modularized application requires: a module-info.java file at the root of the module's source directory declaring the module (module com.example.hello { }), Java source files organized in a directory structure matching their package names beneath that root, compilation using javac with --module-source-path (or a simpler direct approach for a single module), and execution using java with --module-path pointing at the compiled module's location plus --module (or -m) specifying which module and main class to run -- this end-to-end process, while more verbose than the traditional classpath-based javac/java invocation for a single unmodularized class, becomes second nature once the basic module directory/compilation/execution pattern is understood.
// Directory structure:
// src/com.example.hello/module-info.java
// src/com.example.hello/com/example/hello/Main.java

// module-info.java
module com.example.hello {
}

// Main.java
package com.example.hello;
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, modular world!");
    }
}

# Compile
javac -d out --module-source-path src $(find src -name "*.java")

# Run
java --module-path out --module com.example.hello/com.example.hello.Main
Real-world example A developer learning JPMS for the first time works through this exact basic 'Hello World' modularized example, getting hands-on familiarity with the module-info.java syntax and the specific --module-source-path/--module-path/--module command-line flags before attempting to tackle modularizing a genuinely large, complex existing application.

Common follow-ups: How does this command-line compilation/execution process differ when using a build tool like Maven or Gradle instead of invoking javac/java directly?;What does the module-info.java file look like for a module that both requires other modules AND exports/provides its own functionality?