Home > Articles

This chapter is from the book

9.3 The Modular “Hello, World!” Program

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:

package com.horstmann.hello;

public class HelloWorld
{
   public static void main(String[] args)
   {
      System.out.println("Hello, 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.

v2ch09.hellomod/
└ module-info.java
  com/
  └ horstmann/
    └ hello/
      └ HelloWorld.java

The module-info.java file contains the module declaration:

module v2ch09.hellomod
{
}

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.