Let us put the traditional “Hello, World!” program into a module. First, we need to put the class into a package—the “unnamed package” cannot be contained in a module. Here it is:
pubtic ctass HettoWortd
pubtic static void main(String args)
System.out.println(“HeUo, Modular World!”);
So far, nothing has changed. To make a module v2ch09.hellomod containing this package, you need to add a module declaration. You place it in a file named module-info.java, located in the base directory (that is, the same directory that contains the com directory). By convention, the name of the base directory is the same as the module name.
The module-info.java file contains the module declaration:
This module declaration is empty because the module has nothing to offer to anyone, nor does it need anything.
Now, compile as usual:
javac v2ch09.hellomod/module-info.java v2ch09.hellomod/com/horstmann/hello/HelloWorld.java
The module-info.java file doesn’t look like a Java source file, and of course there can’t be a class with the name module-info, since class names cannot contain hyphens. The module keyword, as well as keywords requires, exports, and so on, that you will see in the following sections, are “restricted keywords” that have a special meaning only in module declarations. The file is compiled into a class file module-info.class that contains the module definition in binary form.
To run this program as a modular application, you specify the module path, which is similar to the class path but contains modules. You also specify the main class in the format modulename/classname:
java –module-path v2ch09.hellomod –module v2ch09.hellomod/com.horstmann.hello.HelloWorld
Instead of –module-path and –module, you can use the single-letter options -p and -m:
java -p v2ch09.hellomod -m v2ch09.hellomod/com.horstmann.hello.HelloWorld
Either way, the “Hello, Modular World” greeting will appear, demonstrating that you have successfully modularized your first application.
Source: Horstmann Cay S. (2019), Core Java. Volume II – Advanced Features, Pearson; 11th edition.