Easy Tutorial
❮ Java9 Repl Net Serversocket Socket ❯

Java 9 Module System

Java 9 New Features

One of the biggest changes in Java 9 is the introduction of the module system (Project Jigsaw).

A module is an encapsulation of code and data. The code in a module is organized into multiple packages, each containing Java classes and interfaces; the data includes resource files and other static information.

A key feature of Java 9 modules is the inclusion of a module-info.class file in the root directory of the artifact. The artifact format can be a traditional JAR file or a new JMOD file introduced in Java 9. This file is compiled from the module-info.java source file in the root directory. The module declaration file can describe different characteristics of the module.

In the module-info.java file, we can declare a module using the new keyword module, as shown below. The following is a basic module declaration for a module named com.mycompany.mymodule.

module com.tutorialpro.mymodule {
}

Creating a Module

Next, we will create a module named com.tutorialpro.greetings.

Step 1

Create a folder C:>JAVA\src, and then create a folder named com.tutorialpro.greetings under this directory.

Step 2

Create a module-info.java file in the C:>JAVA\src\com.tutorialpro.greetings directory with the following code:

module com.tutorialpro.greetings { }

The module-info.java file is used to create the module. In this step, we created the com.tutorialpro.greetings module.

Step 3

Add a source code file to the module. Create a file named Java9Tester.java in the directory C:>JAVA\src\com.tutorialpro.greetings\com\tutorialpro\greetings with the following code:

package com.tutorialpro.greetings;

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

Step 4

Create a folder C:>JAVA\mods, and then create a folder named com.tutorialpro.greetings under this directory. Compile the module into this directory:

C:/>JAVA> javac -d mods/com.tutorialpro.greetings 
   src/com.tutorialpro.greetings/module-info.java 
   src/com.tutorialpro.greetings/com/tutorialpro/greetings/Java9Tester.java

Step 5

Execute the module and view the output:

C:/>JAVA> java --module-path mods -m com.tutorialpro.greetings/com.tutorialpro.greetings.Java9Tester
Hello World!

module-path specifies the path where the modules are located.

-m specifies the main module.

Java 9 New Features

❮ Java9 Repl Net Serversocket Socket ❯