Monday, April 26, 2021

Difference Between Java and JavaScript

Java, JavaScript, Core Java, Java Certification, JavaScript Certification, Java Preparation

Java vs JavaScript

Java and JavaScript are programming languages. Java is an object oriented programming language whereas JavaScript is more of a scripting language. Both can be used to make web pages more interactive. However, Java is also used to develop server side applications and standalone programming.

Java

Java is an object oriented programming language. In early 1990s, Sun Microsystems developed the Java language. Initially, it was designed to make small programs for the web browser called applets. But later on, Java was used to create applications based on e-commerce.

There are five main features of Java language:

• Provides more flexibility to develop software applications because of object oriented approach.

• Easy to use as it combines the best properties of other programming languages.

• Allows code written in Java to run on different platforms or Java code is independent of platform.

• The code from the remote source can be executed securely.

• Built-in support for computer networks.

Java also supports automated memory management model that allows developers to get rid of the time consuming method called manual memory management. Programmers can easily do this by implementing automatic garbage collection. But according to some people, Java is slow as well as consumes more memory than other programming languages such as C++.

JavaScript

JavaScript is also a programming language which is used to make web pages more dynamic as well as interactive. Constant downloads from the server are not required in case of JavaScript as it runs on the user’s computer. JavaScript is different from the Java programming language.

Most modern day web browsers have built-in JavaScript. However, JavaScript based web pages can run only if JavaScript is enabled on the web browser and the browser supports it. JavaScript is enabled in most browsers by default.

No special program is required in order to write code in JavaScript as it is an interpreted language. You can use any text editor such as Notepad in order to write JavaScript code. You can also use other text editor that colorizes the different codes making it easier to detect any error.

JavaScript is different from HTML because JavaScript is used to create more dynamic web pages while HTML is a markup language that is used to create static content on the web page.

You can insert the JavaScript code in a HTML file by using the <script> tag. But if you want to use the script in different pages of the website then you can save the scripts in different files with .js extension.

Java, JavaScript, Core Java, Java Certification, JavaScript Certification, Java Preparation
Difference between Java and JavaScript

• Java is an object oriented programming language whereas JavaScript is more of a scripting language.

• JavaScript is used to make the web pages more interactive. However, Java can be used not only to make interactive web pages but can also be used to create server side applications and standalone programming.

• Java uses the concept of classes and objects that makes reuse of the code easier but there is no such thing in JavaScript.

• Java exhibits the properties like inheritance, data encapsulation and polymorphism whereas JavaScript does not.

Wednesday, April 21, 2021

Transfer Object Pattern in Java

It is used when we want to pass data with multiple attributes in one shot from client to server. Transfer Object is a simple POJO class having getter/setter methods and is serialized so that it can be transferred over the network. Server Side business class normally fetches data from the database and fills the POJO and sends it to the client or passes it by value. For clients, the transfer object is read-only. The client can create its own transfer object and pass it to the server to update values in the database in one shot.

Following are the entities of this type of design pattern:

Transfer Object Simple POJO having methods to set/get attributes only

Business Object Fills the Transfer Object with data

Client Either requests or sends the Transfer Object to Business Object

Oracle Java Tutorial and Material, Oracle Java Prep, Oracle Java Preparation, Oracle Java Exam Prep, Oracle Java Certification

Approach:

Step 1: Create a Transfer Object
Step 2: Create a Business Object.
Step 3: Use the StudentBO to demonstrate Transfer Object Design Pattern
Step 4: Verify the output.

Procedure: 

Step 1: Creating a Transfer Object 

Example

// Transfer Object Pattern - Design Pattern
  
// Step 1
// Creating a Transfer Object 
// randomly be named it 'StudentVO.java'
  
// Class StudentVO
public class StudentVO {
    
  // Member variables of class
   private String name;
   private int rollNo;
    
  // Creating a constructor of above class
  StudentVO(String name, int rollNo) {
      
    // This keyword for assignment 
    // to same memory block created
    // for every nae and roll number of student
    this.name = name;
      this.rollNo = rollNo;
   }
    
  // Getting name of student 
   public String getName() {
      return name;
   }
    
  // Setting name of Student 
   public void setName(String name) {
      this.name = name;
   }
    
  // Getting roll number of student 
   public int getRollNo() {
      return rollNo;
   }
    
  // Setting roll number of student 
   public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }
}

Step 2: Creating a Business Object

Example

// Transfer Object Pattern - Design Pattern
  
// Step 2
// Creating a Busines object 
// randomly be named it 'StudentBO.java'
  
// Importing List and ArrayList classes of
// java.util package
import java.util.ArrayList;
import java.util.List;
  
// Class StudentBO
public class StudentBO {
      
   // List is working as a database
   List<StudentVO> students;
   public StudentBO() {
   
      students = new ArrayList<StudentVO>();
       
     // Adding custom inputs 
      StudentVO student1 = new StudentVO("Robert",0);
      StudentVO student2 = new StudentVO("John",1);
      students.add(student1);
      students.add(student2);        
   }
    
   public void deleteStudent(StudentVO student) {
      students.remove(student.getRollNo());
      System.out.println("Student: Roll No " + student.getRollNo() + ", deleted from database");
   }
    
   //retrive list of students from the database
   public List<StudentVO> getAllStudents() {
      return students;
   }
    
   public StudentVO getStudent(int rollNo) {
      return students.get(rollNo);
   }
    
   public void updateStudent(StudentVO student) {
      students.get(student.getRollNo()).setName(student.getName());
      System.out.println("Student: Roll No " + student.getRollNo() +", updated in the database");
   }
}

Step 3: Use the StudentBO to demonstrate Transfer Object Design Pattern

Implementation:  List is acting as DB here as shown in demonstrating Transfer Object Design Pattern.

Example

// Transfer Object Pattern - Design Pattern
// Step 3
  
// Use the StudentBO to demonstrate Transfer Object Design Pattern
// randomly be named it 'TransferObjectPatternDemo.java'
  
public class TransferObjectPatternDemo {
    
  // Main driver method
   public static void main(String[] args) {
       
      StudentBO studentBusinessObject = new StudentBO();
        
     // Print all students
      for (StudentVO student : studentBusinessObject.getAllStudents()) {
         System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
      }
       
      // Update student
      StudentVO student = studentBusinessObject.getAllStudents().get(0);
       
     // Custom input  
     student.setName("Michael");
      studentBusinessObject.updateStudent(student);
        
     // Getting the student
      student = studentBusinessObject.getStudent(0);
      System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
   }
}

Oracle Java Tutorial and Material, Oracle Java Prep, Oracle Java Preparation, Oracle Java Exam Prep, Oracle Java Certification

Step 4: Verifying output

Student : [RollNo : 0, Name : Robert ]
Student : [RollNo : 1, Name : John ]
Student : Roll No 0, updated in the database
Student : [RollNo : 0, Name : Michael ]

Monday, April 19, 2021

Difference Between Package and Interface in Java

The key difference between Package and Interface in Java is that Package helps to categorize the classes methodically to access and maintain them easily while Interface helps to implement multiple inheritances and to achieve abstraction.

Java is one of the most popular programming languages. The main advantage of Java is that it supports Object Oriented Programming. This methodology allows modeling the real world objects in software. A class is a blueprint to create an object. Each object contains data or fields to describe the attributes or the properties and methods to describe behaviors. This article discusses two concepts related to OOP in Java  in Java that are Package and Interface.

What is Package in Java?

Java provides a large number of classes. Keeping all the classes in a single folder can be difficult because it is hard to access. This can affect the program manageability. Java uses packages to arrange classes. It is similar to a folder. Java API groups classes into different packages according to the functionality. Therefore, each package contains a related set of classes.

Example of Packages in Java

Few example packages are as follows. The java.io package contains the input, output supporting classes. It includes File, PrintStream, BufferInputStream etc. The java.net package contains the networking related classes. Some examples are URL, Socket, ServerSocket. The java.awt package contains all the classes required to build Graphical User Interfaces. Those are few Java API packages.

Read More: 1Z0-900: Java EE 7 Application Developer

When the programmer wants to use a certain class in the program, he should import that package. If the programmer wants to use the BufferInputStream class in the java.io package, he should write the import statement as follows.

import java.util.BufferInoutStream;

Below statement will import all the classes in the util package.

import java.util.*;

It is also possible to create user defined packages.

package employee;

public class Employee {

}

According to the above example, the employee is the package name. The Employee class is a part of the employee package. This file saves as Employee.java to the employee package.

Furthermore, it is possible to import a public class from one package to another. Refer the following example.

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified
Figure 01: Class A

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified
Figure 02: Class B

Class A is in package 1, and it contains the public method called display. Class B is in package 2, and it contains the main method. Even though they are in separate packages; class B can create an object of class A by importing package1. After importing package 1, class B has access to the data and methods of class A.

Overall, Package in Java helps to organize the project files. This is very useful when developing large system because it allows storing all the files in methodical way.  In addition to that, the Java API packages allow the programmers to use already existing classes.

What is Interface in Java?


Sometimes the programmer might not know the definition of the method. In this situations, the programmer can only declare the method. An abstract method is a method that does not have a definition. It only has the declaration. When there is at least one abstract method, that class becomes an abstract class. Moreover, the abstract class can contain abstract methods as well as non-abstract methods. The programmer cannot create objects out of abstract classes.

When a class extends an abstract class, the new class should define all the abstract method in the abstract class. In other words, assume that abstract class A has an abstract method called display. Class B extends class A. Then class B should define the method display.

Example of Interface in Java


Assume that both A and B are abstract classes. If class C is extending A and B, that class C has to define the abstract methods of both classes. This is multiple inheritance. Java does not support multiple inheritance. To implement it, the programmer should use interfaces. If A and B are interfaces, then class C can implement them. Refer following example.

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified
Figure 03: Interface A

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified
Figure 04: Interface B

The interface A has the display1 abstract method, and interface B has the display2 abstract method.

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified
Figure 05: Class C

Class C implements both A and B interfaces. Therefore, it should define both methods.

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified
Figure 06: Main Method

Now in the main method, it is possible to create an object of C and call both methods. Likewise, interfaces help to implement multiple inheritance in Java.

Other than multiple inheritance, interfaces help to achieve abstraction. It is one major concept in OOP. Abstraction allows to hide the implementation details and show only the functionality to the user. Further, it allows focusing on what the object does instead of how it is done. As an interface consists of abstract methods, it helps to archive abstraction.

What is the Difference Between Package and Interface in Java?


Package is a group of related classes that provide access protection and namespace management. Interface is a reference type similar to class which is a collection of abstract methods. Package helps to categorize the classes methodically to access and maintain them easily. On the other hand, Interface helps to implement multiple inheritances and to achieve abstraction. This is the main difference between Package and Interface in Java. Further, the way to write a package is in lower case letters such as java.util, java.awt. If the name of the interface is Area, then it is written in, interface Area.

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified

Source: differencebetween.com

Friday, April 16, 2021

JDK

Looking into the JDK 16 vector API

Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career

JDK 16 comes with the incubator module jdk.incubator.vector (JEP 338) which provides a portable API for expressing vector computations. In this post we will have a quick look at this new API.

Note that the API is in incubator status and likely to change in future releases.

Why vector operations?

When supported by the underlying hardware vector operations can increase the number of computations performed in a single CPU cycle.

Assume we want to add two vectors each containing a sequence of four integer values. Vector hardware allows us to perform this operation (four integer additions in total) in a single CPU cycle. Ordinary additions would only perform one integer addition in the same time.

The new vector API allows us to define vector operations in a platform agnostic way. These operations then compile to vector hardware instructions at runtime.

Note that HotSpot already supports auto-vectorization which can transform scalar operations into vector hardware instructions. However, this approach is quite limited and utilizes only a small set of available vector hardware instructions.

A few example domains that might benefit from the new vector API are machine learning, linear algebra or cryptography.

Enabling the vector incubator module (jdk.incubator.vector)

To use the new vector API we need to use JDK 16 (or newer). We also need to add the jdk.incubator.vector module to our project. This can be done with a module-info.java file:

module com.mscharhag.vectorapi {

    requires jdk.incubator.vector;

}

Implementing a simple vector operation

Let’s start with a simple example:

float[] a = new float[] {1f, 2f, 3f, 4f};

float[] b = new float[] {5f, 8f, 10f, 12f};

FloatVector first = FloatVector.fromArray(FloatVector.SPECIES_128, a, 0);

FloatVector second = FloatVector.fromArray(FloatVector.SPECIES_128, b, 0);

FloatVector result = first

        .add(second)

        .pow(2)

        .neg();

We start with two float arrays (a and b) each containing four elements. These provide the input data for our vectors.

Next we create two FloatVectors using the static fromArray(..) factory method. The first parameter defines the size of the vector in bits (here 128). Using the last parameter we are able to define an offset value for the passed arrays (here we use 0)

In Java a float value has a size of four bytes (= 32 bits). So, four float values match exactly the size of our vector (128 bits).

After that, we can define our vector operations. In this example we add both vectors together, then we square and negate the result.

The resulting vector contains the values:

[-36.0, -100.0, -169.0, -256.0]

We can write the resulting vector into an array using the intoArray(..) method:

float[] resultArray = new float[4];

result.intoArray(resultArray, 0);

In this example we use FloatVector to define operations on float values. Of course we can use other numeric types too. Vector classes are available for byte, short, integer, float and double (ByteVector, ShortVector, etc.).

Working with loops


While the previous example was simple to understand it does not show a typical use case of the new vector API. To gain any benefits from vector operations we usually need to process larger amounts of data.

In the following example we start with three arrays a, b and c, each having 10000 elements. We want to add the values of a and b and store it in c: c[i] = a[i] + b[i].

Our code looks like this:

final VectorSpecies<Float> SPECIES = FloatVector.SPECIES_128;
 
float[] a = randomFloatArray(10_000);
float[] b = randomFloatArray(10_000);
float[] c = new float[10_000];
 
for (int i = 0; i < a.length; i += SPECIES.length()) {
    VectorMask<Float> mask = SPECIES.indexInRange(i, a.length);
    FloatVector first = FloatVector.fromArray(SPECIES, a, i, mask);
    FloatVector second = FloatVector.fromArray(SPECIES, b, i, mask);
    first.add(second).intoArray(c, i, mask);
}

Here we iterate over the input arrays in strides of vector length. A VectorMask helps us if vectors cannot be completely filled from input data (e.g. during the last loop iteration).

Source: javacodegeeks.com

Wednesday, April 14, 2021

Java – How to Delete Files and Folders?

Oracle Java, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career

Let us learn the example programs on file deletion and folder removal in java.

1. Java Files Delete Example

First, Use delete() method on the file object to delete the file. Returns true if the file is delete successfully and else return false if there are any failures.

In the below program, we have taken two files test.log file is present in the location and no-file.log does not exists on the location.

Let us see the behaviour of delete() method.

package com.oraclejavacertified.files.delete;

import java.io.File;

/**

 * How to delete the file in java using File api delete() method.

 * 

 * @author oraclejavacertified.blogspot.com

 *

 */

public class FileDelete {

    public static void main(String[] args) {

        // File deletion success

        String fileName = "src/main/java/com/oraclejavacertified/files/delete/test.log";

        File file = new File(fileName);

        boolean isFileDeleted = file.delete();

        if(isFileDeleted) {

            System.out.println("File deleted without any errors for "+fileName);

        } else {

            System.out.println("File deletion is failed");

        }

        // File deletion error.

        fileName = "src/main/java/com/oraclejavacertified/files/delete/no-file.log";

        file = new File(fileName);

        isFileDeleted = file.delete();

        if(isFileDeleted) {

            System.out.println("File deleted without any errors for "+fileName);

        } else {

            System.out.println("File deletion is failed for "+fileName);

        }

    }

}

Output:

File deleted without any errors for src/main/java/com/oraclejavacertified/files/delete/test.log

File deletion is failed for src/main/java/com/oraclejavacertified/files/delete/no-file.log

2. Java Delete Folder Example

Next, we will try to delete the folder which is having the files and next empty folder deletion using delete() method.

package com.oraclejavacertified.files.delete;    

import java.io.File;

/**

 * How to delete the folder in java using File API delete() method.

 * 

 * @author oraclejavacertified.blogspot.com

 *

 */

public class FileDeleteFolder {

    public static void main(String[] args) {

        // Folder deletion not done

        String folderName = "src/main/java/com/oraclejavacertified/files/delete";

        File file = new File(folderName);

        boolean isFileDeleted = file.delete();

        if(isFileDeleted) {

            System.out.println("Folder with files is deleted");

        } else {

            System.out.println("Folder with files is not deleted");

        }

        // Empty Folder deletion success .

        folderName = "src/main/java/com/oraclejavacertified/files/emptyfolder";

        file = new File(folderName);

        isFileDeleted = file.delete();

        if(isFileDeleted) {

            System.out.println("Empty Folder deleted ");

        } else {

            System.out.println("Empty Folder deletion is failed for "+folderName);

        }

    }

}

Output:

Folder with files is not deleted

Empty Folder deleted

Note: if the folder is empty then only folder will be deleted and folder which has files won’t be deleted. But, we can delete the files folder after deleting all files.

Monday, April 12, 2021

Compile and run java9 module program: part2

In the previous post we saw baiscs about java 9 modules like, what is module, how to create module project, module descriptor file and so on. In this blog we will learn how to compile and run java9 module program.

Recommended read: Java 9 module details: part 1

Java9 Module example for hello world

Before going further let’s take an example of hello world module,

Let’s dive deeper with an example, for better understanding we will create two modules. We will put the modules under the folder ‘project’.

First module, we will create is ‘com.module.util’ module. In this module we will create module-info.java and Greeting.java files.

Second module will be ‘com.module.app’ module. In this module we will create module-info.java and Main.java files.

Let’s create two folders for modules as ‘com.module.util’ and ‘com.module.app’ in the ‘project’ folder. These modules contain files Greeting.java and Main.java respectively. Both modules will have module-info.java at top level as shown below.

D:.

├───project

│   ├───com.module.app

│   │   │   module-info.java

│   │   └───com

│   │       └───module

│   │           └───app

│   │                  Main.java

│   │

│   └───com.module.util

│       │   module-info.java

│       └───com

│           └───module

│               └───util

│                      Greeting.java

Note: com.module.util and com.module.app are the folder names

Code for the ‘Greeting.java’ in ‘com.module.util’ module is as below,

Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career, Oracle Java Learning

Code for the ‘Main.java’ in ‘com.module.app’ module is as below,

Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career, Oracle Java Learning

How to compile and run module java program


Now we will see how to run and compile module program. Even if some of the commands look complex don’t worry, once you understand they will be easy and simple.

How to compile and run java program without modules

Before looking into how to run java modular program, let’s understand how to run java package program without using module-info.java file.

To separate out our source files and class files we will use ‘–d’ option to set the destination directory for class files.

Let’s assume we want to run the above Greeting class which is present in the package ‘com.module.util’. And we will put the .class files under the ‘libs’ directory.

D:\project>javac -d libs com.module.util\com\module\util\Greeting.java

Once we execute the above command, we can see that the .class file is created under libs\com\module\util\Greeting.class

Now if we would like to run the main class created by above command, we have to specify path where jvm can find class files. Since our classes are present under libs folder we can specify path using –cp or -classpath.

D:\project>java -cp libs com.module.util.Greeting

OUTPUT

Greeting class is working

Compile and run java 9 module program

Now we have seen how to run java package program and put the classes into separate folder, to avoid mixing .java and .class files. We will use -d option for modular program as well.

Most important thing to remember is that, while compiling module, we have to compile .java source files and module descriptor file(module-info.java) .

In windows path are separated by semi-colon(;) and in Linux and mac using colons(:)

Most important new argument options

There are few new parameters/argument types introduced in java 9 for running the modular program that we must know.

1. module-path: Module-path option is used to specify where the modules are located. It is used at compile and run time.

- At compile time it is used with javac option to specify path where the dependent modules can be found.
Syntax : javac –module-path path1;path2
- At runtime it is used to specify dependent module and module which is to run
Syntax : java -module-path pathslist
Note: we can use -p path as shortcut for –module-path path.

2. module: The –module argument is used to compile list of modules or run a module.

- Syntax : javac –module path1;path2
- Syntax : java –module module/class
Note: we can use -m as shortcut for –module.

3. module-source-path: the argument –module-source-path us used to specify the root directory where the source files or packages are placed.

Sometimes the projects are organized in such a way that the code is placed in special folder.
For example src/main/java

Note: when we are using –module or –m option it is mandatory to use –module-source-path option, even if the source files are in same folder. 
  – – module-path == >  -p 
 – – module       == >  -m 

Example

D:\project> javac -d libs –module-source-path ./ –module com.module.app 
D:\project> java –module-path libs –module com.module.app/com.module.app.Main 

OUTPUT

Have a nice day

Different ways to compile and run java modules


1) We can specify all the files separated by space in javac command:

Warning: If you are using this option don’t compile multiple modules in same folder. Otherwise it will override module-info.class files

Syntax to compile:

javac –d outputDir --module-path requiredModulesPath moduleDir\module-info.java moduleDir\package\File1.java moduleDir\package1\package2\File2.java

Syntax to run:

java --module-path paths --module module/package.MainClass

Note: even in windows in java ‘/’ is used as separator for module and class

Example to compile com.module.util module

D:\project> javac -d libs com.module.util\com\module\util\Greeting.java com.module.util\module-info.java

After this command we should see module-info.class and Greeting.class files are created

project
├───libs
│   │   module-info.class
│   └───com 
│       └───module 
│           └───util 
│                  Greeting.class

Now we can run and check our module using following command

D:\project> java --module-path libs --module com.module.util/com.module.util.Greeting

Greeting class is working

Now lets run the Main class from app module which is dependent on util module which is compiled in libs path.

D:\project> javac --module-path libs -d app com.module.app\com\module\app\Main.java com.module.app\module-info.java

D:\project>java –module-path app;libs –module com.module.app/com.module.app.Main

Have a nice day

2) We can specify module names instead of java files:

This is recommended option to compile the applications. If we use this option, we can compile multiple modules in single directory as separate folder for each module with module name is created.

Also if required modules are in the same folder, they are automatically compiled even if they are not specified

Syntax to compile:

javac –d outputDir --module-path requiredModulesPath --module-source-path rootOfSOurceFiles --module modulesToBeCompiles

Example

D:\project>javac -d libs --module-source-path ./ --module com.module.util,com.module.app

After executing above command, following classes are created

project 
├───libs 
│   ├───com.module.app 
│   │   │   module-info.class
│   │   └───com 
│   │       └───module 
│   │           └───app 
│   │                   Main.class
│   └───com.module.util 
│       │   module-info.class
│       └───com 
│           └───module 
│               └───util 
│                       Greeting.class

Syntax to run:

java --module-path requiredModulesPath --module module/package.MainClass

Example

D:\project>java --module-path libs --module com.module.app/com.module.app.Main

Have a nice day

Common mistakes in running modules


Let’s assume we would like to run Main class from com.module.app module.

Com.module.app module is dependent on com.module.util module.
Com.module.util module is compiled in libs folder
Com.module.app module is compiled in app folder.

When required modules is not specified in module path

java --module-path app -m com.module.app/com.module.app.Main

Error java.lang.module.FindException: Module com.module.util not found, required by com.module.app

When module path of the module which is to be run is not specified in module path

java --module-path libs-m com.module.app/com.module.app.Main

Error: java.lang.module.FindException Module com.module.app not found

When we use the wrong slash(\) to run –correct way is module/class

java --module-path libs;app -m com.module.app\com.module.app.Main

Fast track reading

◉ module-path: used to specify where the modules are located

◉ module: used to specify modules list for compile or module to run

◉ module-source-path: used to specify the root directroy where the source files or packages are places

◉ If we use –-module or –m option it is mandatory to use –-module-source-path option

◉ short codes -p can be used for –-module-path and -m for –module

◉ Syntax to compile javac –d outputDir -p requiredModulesPath –module-source-path rootOfSOurceFiles -m modulesToBeCompiles

◉ Run syntax: java -p requiredModulesPath -m module/package.MainClass

Frequently asked question FAQ:


What is Module resolution process?

When we run the module program, at start jvm checks for all required modules. This process of finding all modules at start is call as Module resolution process.
We can print modules scanning process log by using command –-show-module-resolution in the run command.

Note: in module resolution process first main module is searched then it keep adding required module in tree form.

What are the java restricted keyword or contextual keyword?

Newly added 10 keywords, which are considered as keyword only in case of Module descriptor file(module-info.java), are called as restricted keywords.

This keywords are open, module, requires, transitive, exports, opens, to, uses, provides, and with.
For backward compatibility in every other cases it is considered as identifiers. Unlike other keywords we can use this keywords is variables or method name.

What is module descriptor file?

From java 9, special file with name module-info.java is requied in root folder of module, which specifies the metadata of module, this file is called as module desciptor file.

Can we export multiple package in one line?

No, To export multiple packages separate exports keyword is required.

Can we add multiple modules dependancy using single requries keyword?

No for separate module new requires keyword is required.