Return to site

☕🎓JAVA CERTIFICATION QUESTION: opening module

· ocp,java

Given the modA.jar file with a properly packaged modA module that has the following structure

└──modA

│ module-info.class

│ module-info.java

└───pkg

Main.class

Main.java

and given the following module definition

and the following command

java -p modA.jar -m modA/pkg.Main

What is the result? Choose one.

A. The command fails. To fix it you need to add the following line to module-info.java:

exports pkg;

B. The command fails. To fix it you need to add the following line to module-info.java:

opens pkg;

C. The command fails. To fix it you need to change the pkg.Main class declaration to the following:

public class Main {

D. The command successfully runs and prints Hi.

#java #certificationquestion #ocp

Answer:

The Java command you provided, java -p modA.jar -m modA/pkg.Main, executes a Java program using the specified module path and module.

Let's break it down:

java: It is the command to run the Java Virtual Machine (JVM) and execute Java applications.

-p modA.jar: This option specifies the module path and includes the JAR file modA.jar.

The module path is used to locate modules required by the application.

-m modA/pkg.Main: This option specifies the module and the main class to be executed.

modA is the name of the module, and pkg.Main refers to the fully qualified name of the main class within the module.

Therefore, the command is instructing the JVM to execute the Main class in the modA module, which is loaded from the JAR file modA.jar.

With JPMS, the system enforces encapsulation options such that private Java elements are truly private by default:

Packages cannot be split across modules, and a public element is accessible only within the same module

unless your deliberate directive opens the containing package to other modules.

Despite all this additional encapsulation, the JVM itself still has access to everything.

That’s necessary because it mediates accesses between the elements of your code based on the various directives in the source code.

When the JVM wants to access a main method to launch a program, it does not care if the class that contains that method is public or not.

It also doesn’t care whether the package containing the class is exported.

Knowing this, you can see the command shown for this question would run successfully and print Hi to the console.