How to compile and run using javac and java command in java11 or later
In this blog we will see how to compile and run java class in command line using jdk11.
From java9, modules are introduced in java ecosystem and with that there is a change in the command args to compile or run our class code if we intend to use modules. Please note we can also stick to the old classpath way.
The sample project is available in github and the link to the same is provided at the end. It comprises of one module and an external lib folder.
The project is very simple, which tells the passed text is a number or not.
First we create a module and a class and then add a jar which is needed by the module.
The directory structure looks like below
Compile:
Now to compile the Main.java, go to the project location(sampleJava folder) and run the below command.
C:\Users\surat\git\repository\examples\sampleJava> javac --module-source-path src\modules --module-path lib -d target src\modules\testModule\com\Main.java
- If you look into the structure we now create a modules directory and place our modules src/modules under there and this path will be our module-source-path.
- The module name we define in our module-info.java should match the folder name (testModule)
- External jars directory can be added to our compile command using module-path
- The output of the compilation will be write the directory mentioned after -d option.
- Once compiled the directory will look like

Run:
C:\Users\surat\git\repository\examples\sampleJava>java --module-path target;lib -m testModule/com.Main 23
- Here we again use a new argument module-path which specifies the modules directory the jar location along with our output target folder which contains the classes of our source module separated by ";" in Windows.
- Another argument m which specified the class to run which contains the main method and we need to specify the module of the class name as well.
Link: examples/sampleJava at master · narayanan-surat/examples (github.com)
Comments
Post a Comment