What is the correct way to define a module in Java 9?

Java MCQ: What is the correct way to define a module in Java 9?

a) Using the module keyword in a file named module-info.java
b) Using the class keyword in a file named module.java
c) Using the package keyword in a file named module.java
d) Using the interface keyword in a file named module-info.java

Answer:

a) Using the module keyword in a file named module-info.java

Explanation:

To define a module in Java 9, you use the module keyword in a file named module-info.java. This file is placed in the root directory of the module and contains declarations that specify the module’s name, its dependencies, and the packages it exports.

Here’s an example of a simple module-info.java file:

module com.example.mymodule {
    requires java.sql;
    exports com.example.mymodule.services;
}

In this example, the module com.example.mymodule requires the java.sql module and exports the package com.example.mymodule.services to other modules. This setup enforces strong encapsulation, ensuring that only the specified packages are accessible outside the module.

The module-info.java file is a key component of Java’s module system, enabling better modularization, encapsulation, and dependency management in Java applications.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top