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.

Friday, April 9, 2021

Guidelines for Java code review

Oracle Java Certification, Oracle Java Learning, Oracle Java Preparation, Oracle Java Career, Core Java

Having another pair of eyes scan your code is always useful. It’s helped me get better at writing cleaner code and spot mistakes faster. You need not be an expert to review someone’s code. Some experience with the programming language and a review checklist should help you get started.

The following is a curated list of tips to keep handy while reviewing Java code.

Note: This isn’t an exhaustive list but should help you hit the ground running.

1. Follow Java code conventions

Following language conventions, helps quickly skim through the code and make sense of it, thereby improving readability.

All package names in Java are written in lowercase, constants in all caps, variable names in CamelCase, etc. Find the complete list of conventions here.

Some teams develop their own conventions, so be flexible in such cases!

2. Replace imperative code with lambdas and streams

If you’re using Java 8 +, replacing loops and extremely verbose methods with streams and lambdas makes the code look cleaner. Lambdas and streams allow you to write functional code in Java.

The following snippet filters odd numbers in the traditional imperative way:

List<Integer> oddNumbers = new ArrayList<>();

for (Integer number : Arrays.asList(1, 2, 3, 4, 5, 6)) {

    if (number % 2 != 0) {

      oddNumbers.add(number);

  }

}

Below is the functional way of filtering odd numbers:

List<Integer> oddNumbers = Stream.of(1, 2, 3, 4, 5, 6)

                .filter(number -> number % 2 != 0)

                .collect(Collectors.toList());

class Items {

    private final List<Integer> items;

    public Items(List<Integer> items) {

            this.items = items;

    }

    public Integer highest() {

      if (items.isEmpty()) return null;

      Integer highest = null;

      for (Integer item : items) {

          if (items.indexOf(item) == 0) highest = item;

          else highest = highest > item ? highest : item;

      }

      return highest;

    }

}

Before directly calling a method on an object I recommend checking for nulls as shown below.

Items items = new Items(Collections.emptyList());

Integer item = items.highest();

boolean isEven = item % 2 == 0; // throws Null Pointer Exception ❌

boolean isEven = item != null && item % 2 == 0  // ✅

It can be pretty cumbersome to have null checks everywhere in your code though. If you are using Java 8+, consider using the Optional class to represent values that may not have valid states. It allows you to easily define alternate behavior and is useful for chaining methods.

In the snippet below, we are using Java Stream API to find the highest number with a method which returns an Optional. Note that we are using Stream.reduce, which returns an Optional value.

public Optional<Integer> highest() {
    return items
            .stream()
            .reduce((integer, integer2) -> 
                            integer > integer2 ? integer : integer2);
}
Items items = new Items(Collections.emptyList());
items.highest().ifPresent(integer -> {             // ? ?
    boolean isEven = integer % 2 == 0;
});

Alternatively, you could also use annotations such as @Nullable or @NonNull which will result in warnings if there is a null conflict while building the code ie. passing a @Nullable argument to a method that accepts @NonNull parameters.

3. Directly assigning references from client code to a field


References exposed to the client code can be manipulated even if the field is final. Let’s understand this better with an example.

private final List<Integer> items;
public Items(List<Integer> items) {
        this.items = items;
}

In the above snippet, we directly assign a reference from the client code to a field. The client can easily mutate the contents of the list and manipulate our code as shown below.

List<Integer> numbers = new ArrayList<>();
Items items = new Items(numbers);
numbers.add(1); // This will change how items behaves as well!

In the above snippet, we directly assign a reference from the client code to a field. The client can easily mutate the contents of the list and manipulate our code as shown below.

List<Integer> numbers = new ArrayList<>();
Items items = new Items(numbers);
numbers.add(1); // This will change how items behaves as well!

Instead, consider cloning the reference or creating a new reference and then assigning it to the field as shown below:

private final List<Integer> items;
public Items(List<Integer> items) {
        this.items = new ArrayList<>(items);
}

4. Handle exceptions with care


◉ While catching exceptions, if you have multiple catch blocks, ensure that the sequence of catch blocks is most specific to least. In the snippet below, the exception will never be caught in the second block since the Exception class is the mother of all exceptions.

try {
    stack.pop();
} catch (Exception exception) {
    //handle exception
} catch (StackEmptyException exception) {
    //handle exception
}

If the situation is recoverable and can be handled by the client (the consumer of your library or code) then it is good to use checked exceptions. eg. IOException is a checked exception that forces the client to handle the scenario and in case the client chooses to re-throw the exception then it should be a conscious call to disregard the exception.

5. Ponder over the choice of data structures


Java collections provide ArrayList, LinkedList, Vector, Stack, HashSet, HashMap, Hashtable. It’s important to understand the pros and cons of each to use them in the correct context.

A few hints to help you make the right choice:

Map – Useful if you have unordered items in the form of key, value pairs and require efficient retrieval, insertion, and deletion operations. HashMap, Hashtable, LinkedHashMap are all implementations of the Map interface.

Oracle Java Certification, Oracle Java Learning, Oracle Java Preparation, Oracle Java Career, Core Java

List – Very commonly used to create an ordered list of items. This list may contain duplicates. ArrayList is an implementation of the List interface. A list can be made thread-safe using Collections.synchronizedList thus removing the need for using Vector. 

Set – Similar to list but does not allow duplicates. HashSet implements the Set interface.

6. Think twice before you expose


There are quite a few access modifiers to choose from in Java – public, protected, private. Unless you want to expose a method to the client code, you might want to keep everything private by default. Once you expose an API, there’s no going back.

For instance, you have a class Library that has the following method to checkout a book by name:

public checkout(String bookName) {
    Book book = searchByTitle(availableBooks, bookName);
  availableBooks.remove(book);
  checkedOutBooks.add(book);
}
 
private searchByTitle(List<Book> availableBooks, String bookName) {
...
}

If you do not keep the searchByTitle method private by default and it ends up being exposed, other classes could start using it and building logic on top of it that you may have wanted to be part of the Library class. It could break the encapsulation of the Library class or it may be impossible to revert/modify later without breaking someone else’s code. Expose consciously!

7. Code to interfaces


If you have concrete implementations of certain interfaces (e.g. ArrayList or LinkedList) and if you use them directly in your code, then it can lead to high coupling. Sticking with the List interface enables you to switch over the implementation any time in the future without breaking any code.

public Bill(Printer printer) {
    this.printer = printer;
}
 
new Bill(new ConsolePrinter());
new Bill(new HTMLPrinter());

In the above snippet, using the Printer interface allows the developer to move to another concrete class HTMLPrinter.

8. Don’t force fit interfaces


Take a look at the following interface:

interface BookService {
        List<Book> fetchBooks();
    void saveBooks(List<Book> books);
    void order(OrderDetails orderDetails) throws BookNotFoundException, BookUnavailableException;   
}
 
class BookServiceImpl implements BookService {
...

Is there a benefit of creating such an interface? Is there a scope for this interface being implemented by another class? Is this interface generic enough to be implemented by another class? If the answer to all these questions is no, then I’d definitely recommend avoiding this unnecessary interface that you’ll have to maintain in the future. 

Well then, what’s a good use case for an interface? Let’s say we have a class Rectangle and a class Circle that has behavior to calculate perimeter. If there is a requirement, to sum up, the perimeter of all shapes – a use case for polymorphism, then having the interface would make more sense, as shown below.

interface Shape {
        Double perimeter();
}
 
class Rectangle implements Shape {
//data members and constructors
    @Override
    public Double perimeter() {
        return 2 * (this.length + this.breadth);
    }
}
 
class Circle implements Shape {
//data members and constructors
    @Override
    public Double perimeter() {
        return 2 * Math.PI * (this.radius);
    }
}
 
public double totalPerimeter(List<Shape> shapes) {
    return shapes.stream()
               .map(Shape::perimeter)
               .reduce((a, b) -> Double.sum(a, b))
               .orElseGet(() -> (double) 0);
}

9. Override hashCode when overriding equals


Objects that are equal because of their values are called value objects. e.g., money, time. Such classes must override the equals method to return true if the values are the same. The equals method is usually used by other libraries for comparison and equality checks; hence overriding equals is necessary. Each Java object also has a hash code value that differentiates it from another object.

class Coin {
    private final int value;
 
    Coin(int value) {
        this.value = value;
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Coin coin = (Coin) o;
        return value == coin.value;
    }
}

In the above example, we have overridden only the equals method of Object.

HashMap<Coin, Integer> coinCount = new HashMap<Coin, Integer>() {{
            put(new Coin(1), 5);
            put(new Coin(5), 2);
        }};
        //update count for 1 rupee coin
        coinCount.put(new Coin(1), 7);
 
                coinCount.size(); // 3 🤯 why? 

We would expect coinCount to update the number of 1 rupee coins to 7 since we override equals. But HashMap internally checks if the hash code for 2 objects is equal and only then proceeds to test equality via the equals method. Two different objects may or may not have the same hash code but two equal objects must always have the same hash code, as defined by the contract of the hashCode method. So checking for hash code first is an early exit condition. This implies that both equals and hashCode methods must be overridden to express equality.

Enter DeepSource


I described 10 issues you may come across while reviewing Java code. There is an endless list of issues, though, that could be overlooked by an individual(s). While reviewing code is a good opportunity to learn, it could be a repetitive and tedious task; that’s where DeepSource comes in.

Source: javacodegeeks.com

Wednesday, April 7, 2021

How To Make A File Read Only Or Writable In Java?

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

1. Overview

In this article, We’ll learn how to make a file as read only in java. After creating the file in java, we have to specify the file property readOnly flag to true. But, we can not set this flag to true directly.

File api has a utility method setReadOnly() method which returns a boolean value. True is returned if the file is successfully changed to read only form else false is returned.

Example to convert file from writable to read only and vice-versa.

2. Java Example To Set File As Read Only

Now let us create a class which creates a new File with name make-read-only.txt file. After that just call the method

setReadOnly() method. That’s all now this file is set to only read only operations.

package com.oraclejavacertified.files.readonlywrite;

import java.io.File;

/**

 * Example to set the file as read-only format.

 * 

 * @author oraclejavacertified.com

 *

 */

public class FileReadOnlyExample {

    public static void main(String[] args) {

        File newFile = new File("src/main/java/com/oraclejavacertified/files/readonlywrite/make-read-only.txt");

        // setting the file as read only

        boolean isSetToReadOnly = newFile.setReadOnly();

        System.out.println("isSetToReadOnly value : "+isSetToReadOnly);

        if(isSetToReadOnly) {

            System.out.println("make-read-only.txt is set to read-only form");

        }else {

            System.out.println("Failed to set file as read only for make-read-only.txt");

        }

    }

}

Output:

isSetToReadOnly value : true

make-read-only.txt is set to read-only form

3. Java Example To Check File Can Be Writable

In the above section, we have made the file as read only, but let us check now wether the file is allowed for the modifications or not.

Java File API has another method canWrite() which returns true if the file writable else false that means file is read only.

Look at the below example program. We are just passing the same file name to the File class and directly checking with

canWrite() method.

After that created a new file and checked the canWrite() on the new file object.

Observe the outputs for better understanding.

package com.oraclejavacertified.files.readonlywrite;

import java.io.File;

/**

 * Example to check the file is writable or not.

 * 

 * @author oraclejavacertified.com

 *

 */

public class FileCanWriteExample {

    public static void main(String[] args) {

        File newFile = new File("src/main/java/com/oraclejavacertified/files/readonlywrite/make-read-only.txt");

        // checking the is allowed for modifications.

        boolean isSetToReadOnly = newFile.canWrite();

        System.out.println("Can write the file ? : " + isSetToReadOnly);

        File breandNewFile = new File("src/main/java/com/oraclejavacertified/files/readonlywrite/make-new-file.txt");

        // checking the is allowed for modifications.

        isSetToReadOnly = breandNewFile.canWrite();

        System.out.println("Can write the breandNewFile file ? : " + isSetToReadOnly);

    }

}

Output:

Can write the file ? : false

Can write the breandNewFile file ? : true

4. Java Example To Make Writable from Read Only Form

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Core Java, Oracle Java Prep
Next, let us use the same read-only file and try to change its property to writable using setWritable(boolean).

If true is passed then file becomes writable 

If false is passed then file becomes only readable

Example program is shown below.

This method is very useful when you are working with the unix platform and we can change the files permissions easily from programming.

package com.oraclejavacertified.files.readonlywrite;

import java.io.File;

/**

 * Example to convert the file from read only to writable form.

 * 

 * @author oraclejavacertified.com

 *

 */

public class FileSetWritableExample {

    public static void main(String[] args) {

        File newFile = new File("src/main/java/com/oraclejavacertified/files/readonlywrite/make-read-only.txt");

        // Changing the file from read only to writable format.

        boolean isWritableNow = newFile.setWritable(true);

        System.out.println("Can write the file ? : " + isWritableNow);

    }

}

Output:

Can write the file ? : true

Monday, April 5, 2021

Difference Between Abstract Class and Inheritance

Oracle Java Abstract Class, Oracle Java Inheritance, Oracle Java Career, Oracle Java Prep, Java Preparation

Abstract Class vs Inheritance

Abstract class and Inheritance are two important object oriented concepts found in many object oriented programming languages like Java. Abstract class can be considered as an abstract version of a regular (concrete) class, while Inheritance allows new classes to extend other classes. Abstract class is a class that cannot be initialized but can be extended. So, Abstract classes are only meaningful to have if the programming language supports inheritance. In Java, Abstract classes are declared using Abstract keyword, while Extends keyword is used for inheriting from a (super) class.

What is  Abstract Class?

Typically, Abstract classes, also known as Abstract Base Classes (ABC), cannot be instantiated (an instance of that class cannot be created). So, Abstract classes are only meaningful to have if the programming language supports inheritance (ability to create subclasses from extending a class). Abstract classes usually represent an abstract concept or entity with partial or no implementation. Therefore, Abstract classes act as parent classes from which child classes are derived so that the child class will share the incomplete features of the parent class and functionality can be added to complete them.

Abstract classes may contain Abstract methods. Subclasses extending an abstract class may implement these (inherited) Abstract methods. If the child class implements all such Abstract methods, it is a concrete class. But if it does not, the child class also becomes an Abstract class. What all this means is that, when the programmer nominates a class as an Abstract, she is saying that the class will be incomplete and it will have elements that need to be completed by the inheriting subclasses. This is a nice way to create a contract between two programmers, which simplifies tasks in software development. The programmer, who writes code to inherit, needs to follow the method definitions exactly (but of course can have her own implementation).

What is Inheritance?

Oracle Java Abstract Class, Oracle Java Inheritance, Oracle Java Career, Oracle Java Prep, Java Preparation

Inheritance is an object oriented concept, which allows new classes to extend other classes. Extends keyword is used to implement the concept of inheritance in Java programming language. Inheritance essentially provides code reuse by allowing extending properties and behavior of an existing class by a newly defined class. When a new subclass (or derived class) extends a super class (or parent class) that subclass will inherit all attributes and methods of the super class. The subclass can optionally override the behavior (provide new or extended functionality to methods) inherited from the parent class. Typically, A subclass cannot extend multiple super classes (e.g. in Java). Therefore, you cannot use extends for multiple inheritance. In order to have multiple inheritance, you need to use interfaces.

What is the difference between Abstract Class and Inheritance?

Abstract classes usually represent an abstract concept or an entity with partial or no implementation. Inheritance allows new classes to extend other classes. Because, Abstract classes cannot be instantiated, you need to use the concept of inheritance to make use of Abstract classes. Otherwise, an Abstract class has no use. Abstract classes may contain Abstract methods and when the class is extended, all methods (Abstract and concrete) are inherited. The inherited class can implement any or all the methods. If all the Abstract methods are not implemented, then that class also becomes an Abstract class. A class cannot inherit from more than one Abstract class (this is not a quality of Abstract classes per se, but rather a restriction of inheritance).