How to create a module in Java 9?

JavaObject Oriented ProgrammingProgramming

The module is a package of code and data. The module's code has organized into multiple packages and each package contains java classes and interfaces. The module's data includes resource files and other static information. An important feature of the module is that it contains "module-info.class" file that describes the module in the root directory of its artifacts. The artifact format can be a traditional JAR file or a JMOD file. This file is compiled from the source code file in the root directory.

We can declare a module in file with the new keyword module, the basic module declaration for a module is given below.

module com.tutorialspoint.mymodule {

Steps to create a module:

First Step:

Create a folder C:\JAVA\src and then create a folder com.tutorialspoint.greetings with the same name as the module.

Second Step:

Create a file in the C:\JAVA\src\com.tutorialspoint.greetings directory with the following code.

module com.tutorialspoint.greetings {

Third Step:

Add a source code file to the module, and create a file in the directory C:\JAVA\src\com.tutorialspoint.greetings\com\tutorialspoint\greetings, the code is as follows:

package com.tutorialspoint.greetings;

public class JavaTest {
   public static void main(String args[]) {
      System.out.println("Hello Tutorialspoint!");

Fourth Step:

Create a folder C:\JAVA\mods, and then create a com.tutorialspoint.greetings folder in this directory, and compile the module to this directory.

C:\JAVA>javac -d mods/com.tutorialspoint.greetings src/com.tutorialspoint.greetings/
C:\JAVA>javac -d mods/com.tutorialspoint.greetings src/com.tutorialspoint.greetings/com/tutorialspoint/greetings/

Fifth Step:

Execute the module and see the output

C:\JAVA>java --module-path mods -m com.tutorialspoint.greetings/com.tutorialspoint.greetings.JavaTest
Hello Tutorialspoint!

In the above, module-path specifies the path where the module is located and -m specifies the main module.

Published on 25-Feb-2020 05:54:21