Java Archives - TatvaSoft Blog https://www.tatvasoft.com/blog/category/java/feed/ Thu, 23 May 2024 05:39:15 +0000 en-US hourly 1 Java Best Practices for Developers https://www.tatvasoft.com/blog/java-best-practices/ https://www.tatvasoft.com/blog/java-best-practices/#comments Tue, 22 Aug 2023 05:37:00 +0000 https://www.tatvasoft.com/blog/?p=11749 For any developer, coding is a key task and making mistakes in it is quite possible. Sometimes, the compiler will catch the developer’s mistake and will give a warning but if it is unable to catch it, running the program efficiently will be difficult.

The post Java Best Practices for Developers appeared first on TatvaSoft Blog.

]]>

Key Takeaways

  1. Following a proper set of Java Best Practices enables the entire team to manage the Java project efficiently.
  2. Creating proper project & source files structures, using proper naming conventions, avoiding unnecessary objects and hardcoding, commenting the code in a correct way helps in maintaining the Project Code effectively.
  3. By using appropriate inbuilt methods and functionality, one can easily improve the performance of Java applications.
  4. For exception handling, developers must utilise the catch and finally block as and when required.
  5. By writing meaningful logs, developers can quickly identify and solve the errors.

For any developer, coding is a key task and making mistakes in it is quite possible. Sometimes, the compiler will catch the developer’s mistake and will give a warning but if it is unable to catch it, running the program efficiently will be difficult. And because of this, for any Java app development company, it is essential to make its team follow some of the best practices while developing any Java project. In this blog, we will go through various different types of Java best practices that will enable Java developers to create the application in a standardised manner.

1. Java Clean Coding Best Practices

Here we will have a look at the best practices of Java clean coding –

1.1 Create a Proper Project Structure

Creating the proper project structure is the first step to follow for Java clean coding best practices. Here, the developers need to divide and separate the entire code into related groups and files which enables them to identify the file objectives and avoid rewriting the same code or functions multiple times. 

A good example of the Java Project structure is as follow: 

  • Source
    • Main
      • Java
      • Resource
    • Test
      • Java 
      • Resource

Now, let’s understand each directory in the structure:

Directory Purpose
Main
  • Main source files of the project are stored in the Java folder.
  • Resource folder holds all the necessary resources.
Test
  • Test source files are stored in the Java folder.
  • Test resources files are present in the Resource folder.

Source files refers to the files like Controller, Service, Model, Entity, DTO, and Repositories files, while test source files refers to the test cases files which are written to test the code.

1.2 Use Proper Naming Conventions

Naming conventions mean the names of the interfaces and classes and see how to keep the names of constants, variables, & methods. The conventions set at this stage must be obeyed by all the developers in your team. Some of the best practices that entire team can follow are as follow:

  • Meaningful distinctions: This means that the names given to the variables or other identifiers must be unique and they should have a specific meaning to it. For instance, giving names like i, j, k or p, q, r isn’t meaningful. 
  • Self-explanatory: The naming convention must be such that the name of any variable reveals its intention so that it becomes easy for the entire Java development team to understand it. For instance, the name must be like “dayToExpire” instead of “dte”. This means that the name must be self-explanatory and must not require any comment to describe itself.
  • Pronounceable: The names given by the developers must be pronounceable naturally just like any other language. For instance, we can keep “generationTimestamp” instead of “genStamp”.

Besides this, there are some other general rules that are required when it comes to naming conventions and they are –

  • Methods of the Java code should have names that are starting with lowercase and are verbs. For instance, execute, stop, start, etc. 
  • Names of class and interface are nouns which means that they must start with an uppercase letter. For instance, Car, Student, Painter, etc.
  • Constant names must be in uppercase only. For instance, MIN_WIDTH, MAX_SIZE, etc.
  • Underscore must be used when the numeric value is lengthy in Java code. For instance, the new way to write lengthy numbers is int num = 58_356_823; instead of int num = 58356823;.
  • In addition to this, the use of camelCase notation is also done in Java programming naming conventions. For instance, runAnalysis, StudentManager, and more.

1.3 Avoid Creating Unnecessary Objects

Another best practice for Java clean coding is to avoid creating unnecessary objects. It is known as one of the best memory-consuming operations in Java. This means that the developers must only create objects that are required. 

You can often avoid creating unnecessary objects by using static factory methods in preference to constructors on immutable classes. 

For example, the static factory method Boolean.valueOf(String) is always preferable to the constructor Boolean(String). 

The constructor creates a new object each time whenever it’s called, while the static factory method is not required to do so.

1.4 Create Proper Source File Structure

A source file is something that holds information about various elements. And when the Java compiler enforces any type of structure, a large part of it is fluid. But when some specific order is implemented in a source file it can help in improving the code readability. And for this, there are some different types of style guides available for inspiration for developers. Here is the element’s ordering style that can be used in a source file – 

  1. Package Statement
  2. Import Statements
    • Static and non-static imports
  3. One top-level Class
    • Constructors
    • Class variables
    • Instance variables
    • Methods

Besides this, the developers can also group the methods as per the scope and functionalities of the application that needs to be developed. Here is a practical example of it – 

# /src/main/java/com/baeldung/application/entity/Customer.java
package com.baeldung.application.entity;

import java.util.Date;

public class Patient {
    private String patientName;
    private Date admissionDate;
    public Patient(String patientName) {
        this.patientName = patientName;
        this.admissionDate = new Date();
    }

    public String getPatientName() { 
        return this.patientName; 
    }

    public Date getAdmissionDate() {
        return this.admissionDate;
    }
}

1.5 Comment on the Code Properly

Commenting on the written code is very beneficial when other team members are going through it as it enables them to understand the non-trivial aspects. And in this case, proper care must be taken as specific and to-the-point things must be described in the comments as if not done in a required manner, the comments can confuse developers. 

Besides this, when it comes to commenting on the Java code, there are two types of comments that can be used.

Comment TypeDescription
Documentation/JavaDoc Comments
  • Documentation comments are useful as they are independent of the codebase, and their key focus is on the specification. Besides, the audience of this type of comment is codebase users.
Implementation/Block Comments
  • Implementation comments are for the developers that are working on the codebase and the comments stated here are code implementation-specific.
  • This type of comments can be in a single line as well as in multiple lines depending upon code and steps.

Here, we will have a look at the code that specifies the usage of the meaningful documentation comment:

/**
* This method is intended to add a new address for the employee.
* However do note that it only allows a single address per zip
* code. Hence, this will override any previous address with the
* same postal code.
*
* @param address an address to be added for an existing employee
*/
/*
* This method makes use of the custom implementation of equals 
* method to avoid duplication of an address with the same zip code.
*/
public addEmployeeAddress(Address address) {
}

Implementation Comments:

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!"); 	// This will print “Hello, World!”
    }
}

1.6 Avoid Too Many Parameters in Any Method

When it comes to coding in Java, one of the best practices is to optimize the number of parameters in a method. This means that when any program has too many parameters in a method it can make interpreting the code difficult and complex. 

Let’s have a look at the example of this scenario. Here is the code where there are too many parameters –

private void employeeInformation(String empName, String designation, String departmentName, double salary, Long empId)

Here is the code with an optimized number of parameters –

private void employeeInformation(String empName, Info employeeInfo)

1.7 Use Single Quotes and Double Quotes Properly

In Java programming, single quotes are used to specify characters in some unique cases, and double quotes for strings. 

Let’s understand this with an example: 

Here, to concatenate characters in Java, in order to make a string, double quotes are used as they treat characters as simple strings. Besides this, single quotes specify integer values of the characters. Let’s have a look at the below code as an example – 

public class demoExample
{
 public static void main(String args[]) 
{
  System.out.printIn("A" + "B");
  System.out.printIn('C' + 'D');
}
}

Output:-
AB
135

1.8 Write Code Properly

Code written for any type of application in Java must be easier to read and understand. The reason behind it is that when it comes to Java, there is no single convention for code. Therefore, it is necessary to define a private convention or adopt a popular one. Here are the reasons why it is important and why it is essential to have indentation criteria – 

  • The Java developers must use four spaces for a unit of indentation. 
  • There must be a cap over the line length, but it can also be set to more than 80 owing.
  • Besides this, expressions must be broken down with commas. 

Here is the best example of it – 

List employeeIds = employee.stream()
  .map(employee -> employee.getEmployeeId())
  .collect(Collectors.toCollection(ArrayList::new));

1.9 Avoid Hardcoding

Avoiding hard coding is another best practice that must be followed by developers. For instance, hard coding can lead to duplication and can make it difficult for the developers to change the code when required. 

Besides this, it can also lead to undesirable behaviour when the values in the code are dynamic. Also, hardcoding factors can be refactored in the following manner – 

  • Developers must replace enum or constant value with defined methods or variables in Java.
  • They can also replace class-level defined constants or the values picked from the configuration. 

For Example:

private int storeClosureDay = 7;
// This can be refactored to use a constant from Java
private int storeClosureDay = DayOfWeek.SUNDAY.getValue()

1.10 Review and Remove Duplicate Code

Reviewing the duplicate code is another important best practice that needs to be followed. It can happen that sometimes two or multiple methods have the same intent and functionality in your Java project code. In such cases, it becomes essential for the developers to remove the duplicate methods / class and use the single method / class wherever required.

2. Java Programming Best Practices

Here are some of the best practices of Java coding that developers can take into consideration – 

2.1 Keep Class Members as Private

Class members should be private wherever possible. The reason behind it is that the more inaccessible the member variables are, the better the programming is done. This is the reason why Java developers must use a private access modifier. Here is an example that shows what happens when fields of the class are made public –

public class Student {
  public String name;
  public String course;
} 

Anyone who has access to the code can change the value of the class Student as shown in the below code –

Student student= new Student();
student.name = "George";
student.course = "Maths";

This is why one should use private access modifiers when it comes to defining the class members. The private class members have the tendency to keep the fields hidden and this helps in preventing any user of the code from changing the data without using setter methods. For Example: 

public class Student {
  private String name;
  private String course;
  
  public void setName(String name) {
    this.name = name;
  }
  public void setCourse(String course)
    this.course = course;
  }
}

Besides this, the setter methods are the best choice when it comes to code validation or housekeeping tasks. 

2.2 For String Concatenation, Use StringBuilder or StringBuffer

Another Java best practice is to use StringBuffer or StringBuilder for String concatenation.  Since String Object is immutable in Java, whenever we do String manipulation like concatenation, substring, etc., it generates a new string and discards the older string for garbage collection. These are heavy operations and generate a lot of garbage in the heap. So Java has provided StringBuffer and StringBuilder classes that should be used for String manipulation. These are mutable objects in Java and also provide append(), insert(), delete, and substring() methods for String manipulation.

Here is an example of the code where the “+” operator is used –

String sql = "Insert Into Person (name, age)";
sql += " values ('" + person.getName();
sql += "', '" + person.getage();
sql += "')";

// "+" operator is inefficient as JAVA compiler creates multiple intermediate String objects before creating the final required string.

Now, let’s have a look at the example where the Java developer can use StringBuilder and make the code more efficient without creating intermediate String objects which can eventually help in saving processing time – 

StringBuilder sqlSb = new StringBuilder("Insert Into Person (name, age)");
sqlSb.append(" values ('").append(person.getName());
sqlSb.append("', '").append(person.getage());
sqlSb.append("')");
String sqlSb = sqlSb.toString();

2.3 Use Enums Instead of Interface

Using enums is a good practice rather than creating an interface that is solely used to declare some constants without any methods. Interfaces are designed to define common behaviours and enums to define common values, So for defining values, usage of enums is best practice. 

In the below code, you will see what creating an interface looks like –

public interface Colour {
    public static final int RED = 0xff0000;
    public static final int WHITE = 0xffffff;
    public static final int BLACK = 0x000000;
}

The main purpose of an interface is to carry out polymorphism and inheritance, not work for static stuff. Therefore, the best practice is to start using enum instead. Here is the example that shows the usage of an enum instead of an interface –

public enum Colour {
    RED, WHITE, BLACK
}

In case – the colour code does matter, we can update the enum like this:

public enum Colour {
 
   RED(0xff0000);
    BLACK(0x000000),
    WHITE(0xffffff),
   
    private int code;
 
    Color(int code) {
        this.code = code;
    }
 
    public int getCode() {
        return this.code;
    }
}

As we can see that the code is a bit complex because of the project and in such cases we can create a class that is dedicated to defining constants. An example of this is given below – 

public class AppConstants {
    public static final String TITLE = "Application Name";
 
    public static final int THREAD_POOL_SIZE = 10;
    
    public static final int VERSION_MAJOR = 8;
    public static final int VERSION_MINOR = 2;

    public static final int MAX_DB_CONNECTIONS = 400;
 
    public static final String INFO_DIALOG_TITLE = "Information";
    public static final String ERROR_DIALOG_TITLE = "Error";
    public static final String WARNING_DIALOG_TITLE = "Warning";    
}

By having a look at the code above, we can say that it is an unsaid rule that using enums or dedicated classes is a better idea than using interfaces. 

2.4 Avoid Using Loops with Indexes

Developers must avoid using a loop with an index variable wherever possible. Instead they can replace it with forEach or enhanced for loop. 

The main reason behind this is that the index variable is error-prone, which means that it may incidentally alter the loop’s body, or start the index from 1 instead of starting it from 0. Here is an example that enables the developer to iterate over an array of Strings:

String[] fruits = {"Apple", "Banana", "Orange", "Strawberry", "Papaya", "Mango"};
 
for (int i = 0; i < fruits.length; i++) {
    doSomething(fruits[i]);
}

The above code specifies that the index variable “i”  in this for loop is something that can be easily altered and can cause unexpected results. To prevent this, the developers must use an enhanced for loop like this:

for (String fruit : fruits) {
    doSomething(fruit);
}

2.5 Use Array Instead of Vector.elementAt()

Vector is known as a legacy implementation approach that is used with Java bundle. It is just like ArrayList but unlike it, Vector can be synchronised. It doesn’t require additional synchronisation when multiple threads try to access it but at the same time, it also degrades the performance of the Java application. And when it comes to any application, performance is the most important factor. Therefore, the array must be used instead of a Vector. 

Let’s take an example where we have used the vector.elementAt() method to access all the elements.

int size = v.size();
for(int i=size; i>0; i--)
{
    String str = v.elementAt(size-i);    
}

For best practice, we can convert the vector first into an array. 

int size = v.size();
String arr[] = (String[]) v.toArray();

2.6 Avoid Memory Leaks

Unlike most other programming languages for software development, when developers are working with Java, they do not need to have much control over memory management. The reason behind it is that Java is a programming language that manages memory automatically. 

In spite of this, there are some Java best practices that experts use to prevent memory leaks because any kind of memory loss can degrade an application's  performance and also affect the business. 

There are few more points to prevent memory leaks in Java.

  • Do not create unnecessary objects.
  • Avoid String Concatenation and use String Builder and String Buffer.
  • Don't store a massive amount of data in the session and time out the session when no longer used.
  • Do not use the System.gc() and also avoid using static objects.
  • Always close the connections, statements and result sets in the Finally block.

2.7 Debug Java Programs Properly

Debugging Java programs properly is another practice that developers need to follow. For this, there is nothing much that they need to do. The developers just have to right-click from the package explorers. Then they can select the option Debug As and choose the Java application they prefer to debug. This can help them to create a Debug Launch Configuration which can be utilized by the experts to start the Java application. 

Besides this, nowadays, Java developers can edit and save the project code while they are debugging it without any need of restarting the entire program and this is possible because of the HCR (Hot Code Replacement). HCR is a standard Java approach that is added to enable expert Java developers to experiment with the code and have an iterative trial-and-error coding.

Debugging allows you to run a program interactively while watching the source code and the variables during the execution. A breakpoint in the source code specifies where the execution of the program should stop during debugging. Once the program is stopped you can investigate variables, change their content, etc. To stop the execution, if a field is read or modified, you can specify watchpoints.

Here is a post that describes the unique Java debugging tools:

Quora Question

2.8 Avoid Multiple if-else Statements

Another Java programming best practice is to avoid the usage of multiple if-else statements. The reason behind it is that when conditions like if-else statements are overused, they will affect the performance of the application as JVM will have to compare the conditions every now and then. 

Besides this, using conditions more than required can become worse if the same one is utilized by the developers in looping statements like while, for, and more. Basically, when there are too many statements or conditions used, the business logic of the application will try to group all the conditions and offer the boolean outcome. Here is an example that shows what happens when the if-else statement is overused and why it should be avoided -

if (condition1) {

    if (condition2) {

        if (condition3 || condition4) { execute ..}

        else { execute..}

Note: The above-defined code must be avoided and the developers must use this as follows:

boolean result = (condition1 && condition2) && (condition3  || condition4)  

One can use Switch in place of  if-else. Switch can execute one statement for multiple conditions. It is an alternative of the if-else-if  ladder condition. It also makes it easy to dispatch execution to different parts of code based on value of expression.

// switch statement 
switch(expression)
{
   // case statements
   // values must be of same type of expression
   case value1 :
      // Statements
      break; // break is optional
   
   case value2 :
      // Statements
      break; // break is optional
   
   // We can have any number of case statements
   // below is the default statement, used when none of the cases is true. 
   // No break is needed in the default case.
   default : 
      // Statements
}

2.9 Use Primitive Types Wherever Possible

Java developers should try using primitive types over objects whenever possible as the data of primitive types are on stack memory. While on the other hand, if objects are used, they are stored on heap memory which is comparatively slower than stack memory.

For example: Use int instead of Integer, double instead of Double, boolean instead of Boolean, etc.

Apart from this, developers must also avoid default initialization values to assign while creating any variable. 

Primitive Types

3. Java Exception Handling Best Practices

Here are some of the best practices of Java Execution Handling -

3.1 Don’t Use an Empty Cache Block

Using empty catch blocks is not the right practice in Java programming and the reason behind it is that it can silently fail other programs or continue the program as if nothing has happened. In both cases, it makes it harder to debug the project code. 

Here is an example showing how to multiply two numbers from command-line arguments - (we have used an empty catch block here)

public class Multiply {
  public static void main(String[] args) {
    int a = 0;
    int b = 0;
    
    try {
      a = Integer.parseInt(args[0]);
      b = Integer.parseInt(args[1]);
    } catch (NumberFormatException ex) {
 	// Throwing exception here is ignored
    }
    
    int multiply = a * b;
    
    System.out.println(a + " * " + b + " = " + multiply);
  }
}

Generally, the parseInt() method is used which throws a NumberFormatException Error. But in the above code, throwing exceptions has been ignored which means that an invalid argument is passed that makes the associated variable populated with the default value.

3.2 Handle Null Pointer Exception Properly

Null Pointer Exception occurs when the developer tries to call a method that contains a Null Object Reference. Here is a practical example of the same situation -

int noOfStudents = office.listStudents().count;

Though there is no error in this code, if any method or object in this code is Null then the null pointer exception will be thrown by the code. In such cases, null pointer exceptions are known as inevitable methods but in order to handle them carefully, the developers must check the Nulls prior to execution as this can help them alter or eliminate the null in the code. Here is an example of the same -

private int getListOfStudents(File[] files) {
 if (files == null)
 throw new NullPointerException("File list cannot be null");

3.3 Use Finally Wherever Required

“Finally” block enables developers to put the important code safely. It enables the execution of code in any case which means that code can be executed whether exceptions rise or not. Besides this, Finally is something that comes with some important statements which are regardless of whether the exception occurs or not. For this, there are three different possibilities that can be carried out by the developers, and we will go through all these cases.

Case 1: Here, Finally can be used when an exception does not rise. The code written here runs the program without throwing any exceptions. Besides this, this code executes finally after the try block.

// Java program to demonstrate
// finally block in java When
// exception does not rise 
  
import java.io.*;
  
class demo{
    public static void main(String[] args)
    {
        try {
            System.out.println("inside try block");
            System.out.println(36 / 2);   // Not throw any exception
        }
        
        // Not execute in this case
        catch (ArithmeticException e) {
            
            System.out.println("Arithmetic Exception");
            
        }
        // Always execute
        finally {
            
            System.out.println(
                "finally : always executes");
            
        }
    }
}

Output -
inside try block
18
finally : always executes

Case 2: The second method where Finally is executed after the catch block when the exception rises.

// Java program to demonstrate final block in Java
// When exception rise and is handled by catch
  
import java.io.*;
  
class demo{
    
    public static void main(String[] args)
    {
        try {
             System.out.println("inside try block");
System.out.println(34 / 0);    // This Throw an Arithmetic exception
        }
  
        // catch an Arithmetic exception
        catch (ArithmeticException e) {
  
            System.out.println(
                "catch : arithmetic exception handled.");
        }
  
        // Always execute
        finally {  
          System.out.println("finally : always executes"); 
        }
    }
}

Output -
inside try block
catch : arithmetic exception handled.
finally : always executes

Case 3: The third case specifies the situation where the Finally is executed after the try block and is terminated abnormally. This situation is when the exception rises. In this case, in the end, Finally still works perfectly fine.

import java.io.*;
  
class demo{
    public static void main(String[] args)
    {
        try {
            System.out.println("Inside try block");  
            // Throw an Arithmetic exception
            System.out.println(36 / 0);
        }
  
        // Can not accept Arithmetic type exception; Only accept Null Pointer type Exception
        catch (NullPointerException e) {
            System.out.println(
                "catch : exception not handled.");
        }
  
        // Always execute
        finally {
  
            System.out.println(
                 System.out.println("finally : always executes");

        }
        // This will not execute
        System.out.println("i want to run");
    }
}

Output -
Inside try block
finally : always executes
Exception in thread "main" java.lang.ArithmeticException: / by zero
at demo.main(File.java:9)

3.4 Document the Exceptions Properly

Another best practice for Java exception handling is to document the exceptions of the project. This means that when any developer specifies any type of exception in the method, it must be documented. It helps the developers to keep records of all the information and also enables other team members to handle or avoid exceptions as per the requirement. And for this, the developer needs to add a @throws declaration in the Javadoc while documenting the exceptions and also describing the entire situation. 

If you throw any specific exception, its class name should specifically describe the kind of error. So, you don’t need to provide a lot of other additional information. Here is an example for it - 

/**
* This method does something extremely useful ...
*
* @param input
* @throws DemoException if ... happens
*/
public void doSomething(int input) throws DemoException { ... }

3.5 Do not Log and Rethrow the Exception

When any exception occurs in the application, it must be either logged or carried out with the app or rethrown and let another method be logged in to save the details. Both situations should never be carried out at the same time. 

This means that the exceptions that developers carry out in the application must never log the details and then rethrow the same. Here is an example for the same -

/* example of log and rethrow exception*/
try {
  Class.forName("example");
} catch (ClassNotFoundException ex) {
  log.warning("Class not found.");
  throw ex;
}

3.6 Catch the Most Specific Exception First

Developers must catch the most specific exceptions first. By following this practice, code gets executed easily, and the catch block can be reached faster. 

Here is an example of this where the first catch block enables the system to handle all NumberFormatExceptions and the second one enables handling of all IllegalArgumentExceptions that are not a part of NumberFormatException.

Other Generic Exceptions will be caught in the last catch block.

public void catchMostSpecificExceptionFirst() {
	try {
		doSomething("A message");
	} catch (NumberFormatException e) {
		log.error(e);
	} catch (IllegalArgumentException e) {
		log.error(e)
	} catch (Exception e) {
		log.error(e)
	}
}

4. Java Logging Best Practices

Here are some of the best practices of Java Logging:

4.1 Use a Logging Framework

Using a logging framework is essential as it enables keeping records of all the methods and approaches of the code. And for robust logging, the developers must deal with concurrent access, format log messages, write alternative destinations of logs, and configure all the logs. 

Basically, when the developer is adopting a logging framework, he will be able to carry out a robust logging process without any issues. One of the widely used logging frameworks is Apache Log4j 2 framework. 

Additionally, you can use levels to control the granularity of your logging, for example: LOGGER.info, LOGGER.warn, LOGGER.error, etc.

4.2 Write Meaningful Messages

Another best practice while logging in to Java is to write meaningful messages. If the log events of the project contain meaningful and accurate messages about the given situation, it will be easy for the entire team to read and understand the code while working on it. And if any error occurs in the application, it can be really helpful as they will have enough information to understand and resolve the issue. Here is an example of the same - 

LOGGER.warn("Communication error");

The message must be written as - 

LOGGER.warn("Error while sending documents to events Elasticsearch server, response code %d, response message %s. The message sending will be retried.", responseCode, responseMessage);

The first message will inform you that there is a communication issue in the logging process but it doesn’t specify anything else which means that the developer working at that time on the project will have to find out the context of the error, the name of the logger, and the line of the code that has a warning.  

The second message provides all the information about the logging communication error which means that any developer will get the exact message that is required. This shows that when messaging is done in an easy way, it helps anyone to understand the error and the entire logging system.

4.3 Do not Write Large Logs

Writing large logs is not the right practice as when unnecessary information is incorporated it can reduce the value of the log as it masks the data that is required. It can also create problems with the bandwidth or the performance of the application. 

Too many log messages can also make reading and identifying relevant information from a log file whenever a problem occurs.

4.4 Make Sure You’re Logging Exceptions Correctly

Another Java best practices that the developers must follow while logging the Java code is to make sure that the exceptions are logged correctly. They must not be reported multiple times. Exceptions must be only monitored and reported by using automated tools as they also create alerts.

4.5 Add Metadata

Adding metadata in the logs enables other developers working on the project to find production issues faster. Metadata can be really useful which means that the more they are used the more it is beneficial for the project.

Eg: 

logger.info(“This process is for following user -> {}”,user.getUserName());

5. Conclusion

As seen in this blog, when any developer is developing a Java application, there are many things he must consider as in the long term other experts will be maintaining the same project. For this reason, the developer must create an application by following the Java best practices that are the standardized approaches for it. In this way, in the future, any other developer will be comfortable handling and maintaining the software development project.

The post Java Best Practices for Developers appeared first on TatvaSoft Blog.

]]>
https://www.tatvasoft.com/blog/java-best-practices/feed/ 2
Kotlin vs Java: Detailed Comparison Guide https://www.tatvasoft.com/blog/kotlin-vs-java/ https://www.tatvasoft.com/blog/kotlin-vs-java/#comments Thu, 02 Feb 2023 12:24:23 +0000 https://www.tatvasoft.com/blog/?p=9343 There are few languages more widely used for Android app development and Java and Kotlin are two of them. You'll find that these two languages are really vital, particularly in the field of Android programming. Knowing the distinctions between Kotlin and Java is crucial if you want to acquire a job developing Android apps.

The post Kotlin vs Java: Detailed Comparison Guide appeared first on TatvaSoft Blog.

]]>
There are few languages more widely useful for Android app development – Java and Kotlin are two of them. You’ll find that these two languages are really vital, particularly in the field of Android programming. Knowing the distinctions between Kotlin vs Java is crucial if you are starting to develop Android apps. For instance, you know mobile app development companies can develop mobile applications in Kotlin at a much faster rate compared to Java.

This blog will allow you to have a head-to-head comparison of Kotlin vs Java, as well as learn about its unique features, strengths, and weaknesses.

1. Kotlin

JetBrains, the creator of industry-leading integrated development environments (IDEs) including IntelliJ IDEA, PhpStorm, Appcode, etc., created Kotlin, a strongly typed, broad sense purpose programming language. Kotlin is an an object-oriented and functional programming language that has been deemed “better” than Java while maintaining full compatibility with Java code.

Kotlin, backed by Google, was declared an official Android Development Language in 2017.

1.1 History of Kotlin

History of Kotlin

These are some of the most significant events in Kotlin’s past:

  • Kotlin 1.0 debuted in 2016.
  • In 2017, Google made an official statement that Kotlin would be given premier treatment in Android.
  • Kotlin v1.3 was published in 2018, and it included support for asynchronous programming via coroutines.
  • Kotlin was officially unveiled by Google in 2019 as the company’s recommended language for building Android apps.

So far, take a look at what Kotlin has achieved.

2. Java

Java language was created by Sun Microsystems Inc’s James Gosling in 1995; in 2009, Oracle Corporation acquired the rights to the language. We may refer to Java as a high-level language since it simplifies and streamlines the process of writing, compiling, and debugging Java code.

Java is an Object-Oriented and statically typed programming language that uses classes and follows the “write once, run anywhere” approach. Applications written in Java may be executed on any computer with a Java Virtual Machine (JVM) installed. Java code is very popular and easy to grasp since it is so close to C and C++.

2.1 History of Java

History of Java

Indonesia is home to a stunning island by the name of Java. The java coffee plant is native to this region, and legend has it that the word “coffee” was coined in this area. James Gosling came up with the moniker while sipping coffee on the way to work. Because of the OAK, the group had made the decision to change the name. Silk, Revolutionary, Dynamic, DNA, and Jolt were some of the alternatives. Even though Silk was ultimately chosen, they went with Java since it was novel and popular.

Interesting fact about Java – Do you know how Java got its Name?

Quora
Image Source – Quora Discussion

3. Kotlin vs Java

Now that we have some background, you may be curious about the effect of Kotlin’s popularity on Java. Different people have different thoughts about this issue. Let’s start by comparing and contrasting the arguments put out by either side.

3.1 Null Safety

One of the most well-known sources of frustration for Java programmers is the occurrence of NullPointerExceptions. NullPointerExceptions is based on the premise that users should be allowed to assign a null integer to any object. However, let’s say that users try to utilize a reference to an object that turns out to be null. In that situation, developers will encounter a complication brought about by Java’s NullPointerExceptions.

Here’s a real life example from twitter.

tweet

In comparison Kotlin vs Java, Kotlin does not allow null values to be assigned to variables or objects. To do so would cause compile errors in the code. Thus, Kotlin does not throw any NullPointerExceptions. A null value cannot be assigned to a variable unless the programmer marks it as nullable. One must insert a punctuation mark to do this:

val number: Int? = null

3.2 Extension Functions

As opposed to Java, Kotlin doesn’t need developers to use inheritance to expand class functionalities. In Kotlin, the programmer must add the name of the class being extended as a prefix to the title of the newly formed function employing the “.” notation in order to conduct the extension function.

open class baseClass (x:Int ) {
      ..........
}
class derivedClass(x:Int) : baseClass(x) {
     ...........
}

In Java, you must build a new class and derive the capabilities of the parent class in order to add to the capabilities of an existing class. That is to say, and you can’t use the extend feature because it’s disabled.

class derived-class extends base-class  
{  
   //methods and fields  
} 

3.3 Code

Kotlin’s low code-base requirements are a major differentiator from Java. It’s a short, succinct language that makes less room for mistakes in the code and makes life easier for programmers.

Generally speaking, Kotlin takes less lines of code than Java to express the same functions, which benefits in developing enterprise applications. On top of that, it may be succinct without sacrificing clarity of syntax.

3.4 Coroutines Support

The default behavior of Android is for all elements of a given app to share the same function and thread (the main thread, which handles user interaction). Operations that need a lot of CPU time or network I/O take a long time. Either of these procedures blocks the calling thread until their whole has been finished after they have been started.

Java permits the development of several background threads to handle long processes off of the main thread. The negative is that it’s difficult to keep track of numerous threads at once, which might increase the likelihood of programming mistakes.

Kotlin is similar in that it allows for the creation of numerous threads. However, a superior and more accessible alternative, called coroutines, is presented.

Suspension Process
Coroutines Support

To what end do coroutines serve? Since they don’t need a stack, coroutines let programmers pause the running program and pick it back up later. This paves the way for asynchronous code that gives the impression of being synchronous yet does not block. For this reason, coroutines prevent the need for an excessive number of threads, each of which the developer must eventually manage. They also provide a more precise and streamlined solution than Java.

3.5 Data Classes

The fields (or variables) to hold data, the constructor, and the getter and setter methods for the fields/variables, in addition to ancillary functions like hashCode(), equals(), and toString(), must all be established by developers in Java. Although they may look like they have some functionality, in reality, these classes are just there to hold information.

Instead, the “data” keyword in Kotlin’s class declaration makes it easier to design classes that can store data. Then compiler automatically generate the constructor and numerous getter and setter procedures for fields and variables.

3.6 Smart Casts

Checking the type of parameters in a Java cast ensures that they are compatible with the operation.

The smart casts functionality in Kotlin is responsible for performing the necessary casting tests. The “is-checks” keyword allows Kotlin’s smart compiler to take care of managing repetitive casts (with safe values) efficiently.

fun demo(x: Any) {
    if (x is String) {
        print(x.length) // x is automatically cast to String
    }
}

3.7 Checked Exceptions

However, Kotlin does not provide checked exceptions. That’s why Kotlin programmers don’t need to worry about declaring or catching exceptions. 

Support for checked exceptions is available to Java developers. This necessitates the action of “catching” and “declaring” exceptions. To be sure, it’s not always easy and it does take some time. On the contrary hand, it guarantees error-free and reliable code quality. Consequently, there are both benefits and drawbacks to using checked exceptions. All boils down to the individual preferences of the programmers involved.

3.8 Functional Programming: Higher-Order Functions and Lambdas

Kotlin combines object-oriented and functional programming. Declarative in nature, the functional programming language is well-suited to the management of calculations using mathematical functions. Examples of functional programming ideas include high-order functions and lambda expressions.

The first one implies that functions are of the highest possible importance. This allows the statically typed language Kotlin to achieve most of its many possible functional types. In other words, there are several methods to implement a function.

Lambda expressions and anonymous functions are also supported in Kotlin. The term “functional literal” describes these. Therefore, it stands in for a function that has not been defined but is nevertheless allowed to be used as an expression.

On the other hand, Java is more constrained by the confines of the object-oriented paradigm. But it has also been making progress toward functional programming. Lambda expressions, functions that don’t have to be members of any particular class, have been available in Java since version 8 (2014). As a matter of fact, lambda expressions in Java may be provided as objects and run as needed.

On top of that, high-order functions were finally supported in Java after the advent of lambda expressions. A method in Java is equivalent to a function, and beginning with Java 8, lambda might be returned from methods.

Example of lambda expression: 

In Kotlin:

val sum: (Int, Int) -> Int = { a: Int, b: Int -> a + b }

In Java:

int sum = (a,b) -> (a+b);

3.9 Primitive Types

Primitive Types

Primitive type variables in Java are not objects, but rather are predeclared data kinds in Java. There are eight distinct primitive data types available in Java: int, byte, short, double, float, boolean, char, and long. As a result, you can’t use structs or classes to describe these variables.

In Java, classes can be created to “wrap” a value of a basic type, even if primitive types themselves are not classes. It requires an explicit developer indication in Java.

Kotlin, on the other hand, treats any primitive type variable as an object as immediately as it is initialized.

3.10 Public Fields

Java supports public fields, often known as non-private fields. They allow the developer to alter an object’s description without affecting the callers, which may be very useful in cases when the callers of an object want to adapt to the object’s new representation. The fields may then be made public, preserving both the public API and the project’s supportability.

However, In Kotlin, a field is used as a part of a property to hold its value in memory. Here, one can not declare the fields directly. 

3.11 Wildcard Types

In most programming languages, the question mark (?) is used as a wildcard to indicate a type that has not yet been defined (of variable, field, or parameter).

Wildcards are not supported in Kotlin like they are in Java. It replaces them with a declaration-site variant and type projections.

3.12 Implicit Conversions

While other languages may allow for implicit widening conversions, Kotlin does not. Because of this, there is no way to transform a smaller type into a larger type. Developers working in Kotlin will run across this problem unless they do an explicit conversion to get the appropriate type.

In contrast, developers don’t have to worry about performing explicit conversions while working with Java because the language enables implicit conversions.

Example: 

Java:

public class myClass{ 
   public static void main(String args[]) { 
      int a = 81; 
      System.out.println("Integer value : "+a);   // Implicit Type Casting 
      long b = a;                                // Int val to long data type                                            
   }
}

But in Kotlin, we can not directly assign integer value to the long data type.

var x = 100
var y : Long = x       
// Compiler error
// Type mismatch: inferred type is Int but Long was expected


var x = 100
var y: Long = x.toLong()     
// compiles successfully

4. Tabular Comparison: Kotlin vs Java

Parameters Kotlin Java
Static members No static members exist for a class. It has static members for a class.
NullPointerException When writing in this language, you may use the safety call operator to implement null safety. Null safety is not provided in java.
Wildcards Wildcard types are not accessible. It is possible to use wildcards in several forms. These are a subset of type arguments that regulate how generic (parameterized) types can be used without compromising on type safety.
Deployment Coding in Kotlin is simple to deploy. Tough to deploy Java programs.
Secondary Constructor There is an idea of secondary constructors in Kotlin. Furthermore, more than one tertiary builder is possible. It allows variables to be initialized and adds logic to the class. No such concept here, however, it is possible to have more than one constructor.
Semicolon In Kotlin code, a semicolon is not necessary. Java code always needs semicolons.
Expressions Kotlin’s string template further supports expressions, which can include variables, operators, and method calls. Expressions are not supported by Java strings in the same way that they are in Kotlin.
Lazy loading Kotlin also offers the option of Lazy Loading, which is a convenient time-saving function. It is favored in cases where the property’s initialization has a significant effect on computing resources (such as memory, CPU, etc.). Unlike other programming languages, Java does not support lazy loading.
DataType There is no necessity to define the data type of each variable. It is necessary to specify the data type of each variable.
Smart cast It has a function called “smart cast”. To clarify, the Kotlin compiler does not ignore the condition inside an if statement.  Smart cast is available.
Annual Salary Depending on the position, the typical annual income for Kotlin ranges between $68k – $135k in the USA. A Java developer’s annual pay ranges between $92k-$180k in the USA.

5. Unique Features of Kotlin

  • High-performing user-defined flow control with lambda expressions and inline functions
  • Moduli of extension
  • Null-safety
  • The use of savvy casting techniques
  • Template strings
  • Properties
  • Essential builders
  • Superior delegation
  • Inferring the nature of a variable or property from its context
  • Singletons
  • Variation in declaration locations and expected type
  • Range expressions
  • Operator overloading
  • Companion objects
  • Structures of information
  • Separate user interfaces for immutable and readable collections
  • Coroutines

6. Pros and Cons of Kotlin

6.1 Benefits of Using Kotlin

  • You may use the Kotlin Multi platform framework to simultaneously target many platforms from a single codebase.
  • Kotlin’s built-in null safety support is a godsend, particularly on Android with its abundance of legacy Java-style APIs.
  • Compared to Java, it has less space for error since it is more succinct and expressive.
  • Provides accessible and comprehensible code standards
  • Breaks down complex programs into manageable chunks.
  • Utilizes a wide variety of function types and advanced language constructs like lambda expressions.
  • Facilitates the addition of new features by developers
  • Provides a straightforward, nearly hands-off method of defining data classes.
  • Kotlin’s simple syntax and readable type system make it an ideal language for beginners.
  • Information from Java may be transferred and used in a number of different contexts thanks to this language.
  • Kotlin will speed up the process of creating new code.
  • The process of deploying and maintaining scalable Kotlin code is significantly less complicated.

6.2 Disadvantages of Kotlin

  • Due to the small size of the developer community, educational resources and expert guidance are in short supply.
  • In Java, you won’t find any error-prevention features like checked exceptions.
  • Taking longer to compile than Java.
  • Due to Kotlin’s declarative nature, it might be useful to produce substantial quantities of boilerplate in the form of JVM bytecode.

7. Unique Features of Java

  • Checked exceptions.
  • Primitive types in Java are not objects. 
  • Java code compiles faster than the Kotlin one. 
  • It supports ternary operator (a?b:c)
  • Java supports implicit conversion. So that one can directly convert smaller types into bigger ones.

8. Pros and Cons of Java

8.1 Benefits of Java

  • Improved issue detection and resolution thanks to checked exceptions
  • It comes with a manual that details everything.
  • Java has a  sizable pool of talented programmers.
  • Comprehensive third-party library support.
  • You may use it to create repeatable code and consistent applications.
  • It’s a multi-threaded setting where many tasks can be executed in the same software at the same time.
  • Excellent performance.
  • Library catalogs that are a breeze to use.

8.2 Disadvantages of Java

  • Due to its many restrictions, Android API architecture is not a good fit.
  • Calls for a lot of manual labor, which raises the possibility of mistakes.
  • This is because the JIT compiler causes the application to run more slowly than usual.
  • Java’s memory and CPU demands are rather high.
  • No help for pointers and other low-level programming structures is included.
  • The trash collector is completely out of your hands because Java lacks standard control methods like delete(), free().

9. Java Issues That are Addressed in Kotlin

Kotlin addresses some shortcomings of Java:

  • The type system regulates the use of null references.
  • There aren’t any unrefined individuals here.
  • In Kotlin, arrays are of fixed  size.
  • If you’re used with Java’s SAM-conversions, you’ll be pleased to know that Kotlin provides appropriate function types.
  • Use-site variance without wildcards.
  • Unfortunately, Kotlin does not provide checked exceptions.

10. Is Kotlin Replacing Java?

When comparing Kotlin vs Java, which has its own set of challenges, Kotlin emerges victorious, particularly when dealing with Null pointer exceptions. Kotlin’s characteristics, such as a superior type system, gradual modification of code, and less coding, make it more attractive for future usage, despite Java’s continued importance for android development.

Kotlin is quickly becoming a go-to language for creating Android apps since it encourages developers to try out new techniques and approaches in the realm of current programming. Kotlin is nearly identical to Java, so it’s a safe bet that it’ll do all that a good programming language should.

The post Kotlin vs Java: Detailed Comparison Guide appeared first on TatvaSoft Blog.

]]>
https://www.tatvasoft.com/blog/kotlin-vs-java/feed/ 2
Java vs C# – Which One to Choose? https://www.tatvasoft.com/blog/java-vs-c/ https://www.tatvasoft.com/blog/java-vs-c/#comments Wed, 04 Jan 2023 05:31:13 +0000 https://www.tatvasoft.com/blog/?p=9129 When it comes to creating a software solution that can be beneficial for any type of business organization, both Java and C# are the best choices available in the market. These back-end development languages can be used for creating windows-client apps, cloud apps, and more.

The post Java vs C# – Which One to Choose? appeared first on TatvaSoft Blog.

]]>
When it comes to creating a software solution that can be beneficial for any type of business organization, both Java and C# are the best choices available in the market. These back-end development languages can be used for creating windows-client apps, cloud apps, and more. These languages come with a lot of similarities but despite them, they aren’t the same. Therefore, when it comes to hiring developers for your project or when the software development company has to decide which language to work on for a particular client project, the best thing to do is understand the key differences between Java vs C#.    

JAVA is object oriented programming language, while C# is object-oriented, component-oriented, functional, and strongly typed programming language. Also, JAVA uses JRE (Java Runtime Environment), whereas C# uses CLR (Common Language Runtime). To help you further, here we will understand both of these languages and then go through the difference between Java vs C#. 

1. Java

Java is one of the most popular programming languages that was developed at Sun Microsystems by James Gosling in 1995. It was later taken into possession by the Oracle Corporation in the year 2009. Java is known as a high-level programming language that makes it very easy for developers to write the code, compile it, and debug the program. Being a Java development company, our developers find this language as a user-friendly programming language that comes with a class-based object-oriented approach that is helpful in implementing the principle of “write the code once and use anywhere”. Java applications that are written once but used to develop other programs are compiled to bytecode and they can run on machines that are JVM (Java virtual machine)-supported.

JDK (Java Development Kit) holds 14.8k stars, 309 watching, and 4.2K forks on GitHub.

GitHub - Java

Features of Java

Features of Java

Some of the major features of the Java programming language are –

Object Oriented Language

Object-oriented programming is one of the most popular ways of organizing programs. The reason behind it is that this concept collects objects and each of the objects represents an instance of a class. The four main concepts that object-oriented programming has to offer are – Abstraction, Encapsulation, Inheritance, and Polymorphism.

Platform-Independent Language

When it comes to Java programming language, the compiler(javac) has the capability to convert source code (.java file) to the byte code(.class file). As discussed before, JVM executes the bytecode that is developed by the compiler. This byte code can run on platforms like Mac OS, Windows, Linux, etc. Basically,  if the Java program is compiled on Windows, it can run on Linux or Mac OS and vice-versa. Though each operating system comes with a different JVM, the output created by them after the bytecode’s execution is the same in all operating systems. This is the reason Java is known as a platform-independent language.

Platform Independent Language - Java

Simple

Java is known as a very simple programming language and the reason behind it is that Java doesn’t come with complex features like multiple inheritances, operator overloading, explicit memory allocation, and pointers.

Secure

In Java, there are no pointers available which mean  the web development team cannot access out-of-bound arrays and if the developers try to do that, they will receive an ArrayIndexOutOfBoundsException error in java.

Example: 

class HelloWorld {

    public static void main(String[] args) {

        int a[] = new int [2];

        a[0] = 5; 

        System.out.println(a[3]);

    }

}

Output:

Output - ArrayIndexOutOfBoundsException error

This is the reason why it is impossible in Java to have security flaws like buffer overflow or stack corruption. But still Java recommends using secure coding guidelines to give an extra layer of security.  

Robust Language

Java is definitely a robust or reliable programming language and this is because of the way it has been developed. It emphasizes a lot on early checking for possible errors which is the main reason why the java compiler can easily detect errors that are not easy to find. One of the main features of the Java platform is that it is robust when it comes to garbage collection, memory allocation, and exception handling.  Even Java Guides mentioned a few Java exception handling best practices in their recent tweet.

Distributed

With the use of Java programming language, the developers can easily create distributed apps as Java comes with EJB(Enterprise Java Beans) and RMI(Remote Method Invocation) which are used for developing distributed applications. Basically, Java can program distributed apps that can run on more than one system that is connected to each other via the internet.

Multithreading

Java supports the multithreading concept. This approach is one of the best features of the Java programming language and it allows concurrent execution of multiple parts of a program to utilize the CPU at its maximum level.

2. C#

C# is a very popular, modern, general-purpose, and object-oriented and component oriented programming language. It is pronounced as C sharp. This language was created by Microsoft led by Anders Hejlsberg and his team. C# programming language was approved by International Standards Organization (ISO) and European Computer Manufacturers Association (ECMA). It is a language that is a lot more similar to Java syntactically and is very easy for developers who have basic knowledge of languages like C, C++, or Java.

C# holds 9.5k stars, 689 watching, and 970 forks on GitHub.

GitHub - C#

Features of C#

Features of C#

Some of the major features of C# are –

Simple

It is a very simple programming language that comes with a rich set of functions, data types, libraries, etc. In C#, the pointers are missing and manipulation of direct memory is unsafe. Besides this, there is no use of operators like, “::” or “->” in C#.

Rich Library

The C# programming language comes with rich libraries that enable the developers to code very easily and as it has many inbuilt functions, programming with this language is fast and easy.

Modern Programming Language

C# is known as a language that has the capability to mold according to the current trend. And for developers, it is a very easy, simple, and powerful language especially when it comes to developing interoperable, scalable, and robust applications.

Object-Oriented

The C Sharp programming language is also known as object-oriented language as it supports polymorphism, interfaces, data encapsulation, and inheritance. The object-oriented programming concept makes development maintenance easier in C#.

Component-Oriented

C# is both Object Oriented and Component Oriented Programming language. To directly support both the concepts, C# provides language constructs. So, one can create and use software components easily.

Fast Speed

When it comes to creating applications using the C# language, there are many inbuilt functions that can be used by developers to write the code. This is why the code in C# doesn’t show any error while compilation and execution which makes it a faster language.

Interoperability

C# language introduces primary support for windows based applications which means that it enables restricted use of native pointers while developing a program.

3. Java vs C#: Key Differences

Before going through the key differences and similarities between Java and C#, Let’s  have a look at the chart which proves the popularity of these two languages. This chart by Stack Overflow shows the percentage of the questions users ask about these languages.

Stack Overflow - Java vs C#

Here are the points that show the key differences between Java vs C# languages –

Parameters Java C#
Ecosystem Java comes with a huge open-source ecosystem. C# is used to create software for various Microsoft platforms.
Programming ParadigmObject oriented programming approach Object-oriented, component-oriented, functional, and strongly typed approach
Runtime environmentJAVA runs on JRE (Java Runtime Environment) C# runs on CLR (Common Language Runtime)
Support for DelegatesJava requires the use of an interface to get similar functionality. C# serves as a method that can be known without knowing the target object.
Support for Generics Java can be implemented with the use of casts and  erasures which can be added into bytecode upon compilation. In C#, the code is integrated into the CLI and it enables the availability of type information at runtime
Support for Operator Overloading Java doesn’t support operator overloading C# supports operator overloading
Support for Pointers Java doesn’t support pointers. C# supports pointers in a function of code block when it is marked by the unsafe modifier
Arrays In Java, arrays are a direct specialization of Object. In C#, arrays are a specialization of the System.
Suited For It is best suited for complex and concurrency projects. It is best suited for game app development.
Platform Dependency Java is a platform-independent and robust language. Code C# is a windows specific language.
Companies Using It Companies like Airbnb, Spotify, Instagram, and Netflix use it. Companies like Codorus, Stack Exchange, Docplanner, and Microsoft use it.

4. Similarities Between Java and C#

Here are the points that show the key similarities between both Java and C# languages –

  • Object-Oriented: Both Java and C# are object-oriented languages and they support concepts like polymorphism, encapsulation, inheritance, and more.
  • Syntax: Both of these languages are syntactically similar.
  • Intermediate Language Code Generation: Java and C# compilers have the capability to generate an intermediate language code after compilation.
  • Dependence on C and C++: C and C++ are the languages that can be called the superset to C# and Java.
  • Advance Features: One of the most beneficial advanced features that these languages come with is garbage collection.
  • Multiple Inheritance: Both Java and C# support single class inheritance.

Besides these points, one other similarity between these languages is that both Java and C# have made it to the list of top 10 most popular technologies in the survey conducted by Stack Overflow. You can see this in the below image.

Similarities Between Java and C#

5. When is Java Preferable over C#?

  • When the developer wants to take advantage of the extensive codebase and community of the language, Java can be used.
  • Java is preferred when the development team wants to create web-based or server or desktop-based apps.
  • Java can be the best choice when one needs portability and interoperability more than efficiency.

6. Pros and Cons of Java

Advantages of Java

  • Allows the app development of reusable code and standard programs.
  • Offers a wide range of skilled developers
  • Provides detailed documentation
  • Easy to navigate libraries
  • High-performance and excellent apps
  • Offers a multi-threaded environment
  • A huge array of third-party libraries

Disadvantages of Java

  • The JIT compiler in Java makes the app slow.
  • It doesn’t offer support for low-level programming.
  • Java demands high processing and memory requirements.

7. When is C# Preferable over Java?

  • C# can be preferred when it comes to developing programs on the .NET platform.
  • Developers choose C# as it enables the software to run efficiently and fast.
  • It offers a modern quality-of-life feature known as garbage collection.
  • When it comes to creating mobile or gaming apps, C# is used.

8. Pros and Cons of C#

Advantages of C#

  • Language-Integrated Query (LINQ)
  • C# offers lambda and generics support.
  • Properties with getting & setting methods
  • Secure extension methods
  • Cross-platform support
  • Memory management
  • Backward compatibility

Disadvantages of C#

  • C# is a part of the .NET framework which means that the apps are based on windows.
  • It offers a poor GUI.
  • Software is proprietary and this means that it requires an upfront purchase.

9. C# and Java Examples

C# language is used by many popular companies and some of them are –

C# Examples
  • Windows Microsoft
  • Alibaba
  • XML for Windows Installer
  • Intuit
  • Open Dental
  •  Microsoft Visual Studio
  • ViaVarejo
  • Stack Overflow
  • Delivery Hero
  • OpenRA
  • FlashDevelop

Java has also been used by some remarkable companies, like –

Java Examples
  • Netflix
  • Pinterest
  • Uber
  • Spotify
  • Twitter 
  • Airbnb
  • Amazon
  • Google
  • CashApp
  • Instagram

10. Conclusion

This detailed comparison of Java vs C#, we can see that both of these languages are best in their own way, and choosing one of these is a very difficult choice for any software developer. Each of these languages comes with unique aspects and using them can be a win for any business organization or software development company. But which language suits which type of application is completely based on the type of application, the budget of the app, the environments a business owner wants his app to run on, and more. And this decision can be taken by the developers when they get hired for a project as they can easily understand the project requirements and decide which between Java vs C# is the best fit.

The post Java vs C# – Which One to Choose? appeared first on TatvaSoft Blog.

]]>
https://www.tatvasoft.com/blog/java-vs-c/feed/ 2
Why Do We Need Java Reactive Programming? https://www.tatvasoft.com/blog/java-reactive-programming/ https://www.tatvasoft.com/blog/java-reactive-programming/#comments Wed, 30 Nov 2022 08:40:38 +0000 https://www.tatvasoft.com/blog/?p=9117 Reactive programming is a programming model for constructing asynchronous and non blocking elements. It is a trending topic right now, and there's a lot of chatter going around it. However, as a Java development company we are always ready to clear the doubts surrounding new Java topics and trends.

The post Why Do We Need Java Reactive Programming? appeared first on TatvaSoft Blog.

]]>
Reactive programming is a programming model for constructing asynchronous and non blocking elements. It is a trending topic right now, and there’s a lot of chatter going around it. However, as a Java development company we are always ready to clear the doubts surrounding new Java topics and trends. Although this will also help our clients to know more about Java Reactive programming.

Some ideas might disappear over time, only to reappear as new ideas when you apply them to a different setting. The identical situation has occurred with Java reactive programming.

What is the definition of reactive programming? What advantages can reactive programming provide as Java applications? Let’s delve further into this subject, relate it to imperative programming, and emphasize the benefits of this programming style for both apps and businesses.

The terms Java Reactive Programming and Functional Reactive Programming (FRP) are common. Even though they are fundamentally distinct, the notions of concurrent programming and excellent performance are often confounded with reactive programming to the point where it is difficult to distinguish them. The result is certain chaos.

Many believe that Reactive is just another version of what they already do every day (mostly they use JavaScript). Some others attribute it to Microsoft, which just made a huge deal out of releasing C# enhancements. There has been a lot of talk about Reactive Streams and other similar projects in the Enterprise Java community as of late. However, there are many misconceptions regarding the appropriate contexts in which to employ these technologies. Let us get a clearer picture of that!

1. Why Do We Need Reactive Programming?

Asynchronous programming is often useful to make systems quick and responsive when dealing with large amounts of data or multiple users. Especially with Java, which is a throwback to the early days of object-oriented programming, asynchronicity may cause a lot of problems and make the code difficult to comprehend and maintain. Consequently, in this strictly object-oriented context, reactive programming is hugely useful since it streamlines the management of asynchronous processes and deals with asynchronous data streams.

Meanwhile, we will also focus on how Reactive Programming serves as a catalyst for developing a Reactive System to help us comprehend the logic behind this creation better.

Reactive Programming

2. What are Reactive Systems? 

A reactive system is an architectural style that allows applications to compose multiple microservices to work together, reacting to their surroundings and one another. Such systems are designed to be more responsive, elastic, and resilient by using asynchronous message-driven communication, which can be helpful features for various applications.

Basically, it is a computer systems paradigm that takes advantage of the flexibility and responsiveness provided in reactive programming so that databases, servers, and software applications can continue to thrive if any of the components is compromised.

Apart from this, it provides productivity for Architects and DevOps at the system level and allows you to build large-scale distributed systems. Also, reactive systems are useful to work with Reactive Programming within the components of a Reactive System.

3. What Does Reactive Manifesto Mean In Reactive Systems?

The Reactive Manifesto was created in 2013 by a group of developers led by Jonas Boner to describe a set of fundamental principles. This is the premise upon which the architecture style necessary to develop Reactive Systems was established. This manifesto has now garnered considerable attention in the programming world.

This document lays out the steps necessary to create a scalable, adaptable, and loosely-coupled reactive system. This paves the way for simple development, fault tolerance, and most all, high responsiveness, all of which are necessary for creating amazing user experiences.

The manifesto lays forth the defining features and guiding ideas of a reactive system, including:

Responsive: A reactive system’s quick and constant reaction time, and by extension, service quality, is what makes it reactive.

Resilient: A reactive system should be robust if it is to continue responding in the face of random breakdowns.

Elastic: An elastic system is one that can accommodate fluctuating loads without incurring excessive costs.

Message-driven: It must rely on the exchange of asynchronous messages between various parts of the system.

Reactive Systems

Although these ideas make perfect sense, applying them to complicated corporate architecture may be difficult. Here we’ll build a simple Java system that exemplifies these guidelines.

4. Difference Between Reactive Programming and Reactive Systems, Are They Both the Same?

They are not. In fact, they are commonly used interchangeably, these phrases really mean different things.

To take ‘reactivity’ to its logical conclusion, we have reactive systems. In order to develop software applications that are robust, versatile, and responsive, a number of architectural and design choices must be made at this stage.

In reactive systems, using reactive programming is not required but recommended since it increases the advantages your software receives from both approaches, such as loose coupling, better use of system resources, faster response times, and reduced latency.

5. Java Reactive Programming, How is it Done?

The Reactive Programming has less of an impact on available memory while delivering better performance for Java programs. It’s accomplished by avoiding OS process and context transitions caused by blocked calls.

Since the number of users and the complexity of their requests have grown, it is desirable to implement the Reactive Programming strategy in modern web applications. Program execution is viewed as an asynchronous series of events in Reactive Programming.

The core reactive components of Java reactive programming are as follows:

  • Observables (a data source/stream that may emit zero, one, or more values; may also produce mistakes; may have a finite or indefinite length);
Observables
  • Users (those who have subscribed to an Observable in order to take use of the data it provides and receives notifications of any failure or success);
  • Build, modify, analyze, and integrate Observables with the help of Operators;
  • Schedulers that enable us to add concurrency to our Observables and Users without difficulty.

Data streams that carry actions, requests, notifications, and failures will form the backbone of your application while utilizing reactive programming. You may monitor the streams using Reactive Programming and act whenever a value is delivered. The developer generates streams in the code for everything that might change or occur (click events, cache events, HTTP requests, etc.), turning the program into an asynchronous one. 

There has been a lot of activity required in providing Reactive layers on top of the JDK. Let’s take a look at a few of them.

ReactiveX

ReactiveX (Reactive Extension) provides a fantastic toolset for incorporating Reactive Programming modules into an application and composing asynchronous, event-driven applications with an observable series.

Reactive Streams

Reactive Stream is an inferior contract defines as a handful of Java interfaces but is also suitable for other languages. It is an initiative to deliver a prototype for the asynchronous stream that is processed with non-blocking explicit back pressure and assembles a standard language for interoperable libraries.

Reactor

Reactor is a fourth-generation Java framework from the Pivot open-source team that is based on Reactive Streams. It allows you to build directly on Reactive Streams, so you don’t require to form a bridge. 

Spring Framework 5.0

Spring Framework 5.0 provides comprehensive programming for modern Java-based enterprise applications. It is an open-source platform that aims to simplify the complex Java application development process. It has several built-in reactive features which include tools for creating HTTP servers and clients.

Ratpack

Ratpack is a collection of JVM-based libraries that are useful for building high-performance services over HTTP. It is developed on a Netty event-driven networking engine with the reactive design pattern and implements Reactive Streams for interoperability.

Akka

Akka is a source-available toolkit for building concurrent applications on the JVM. According to David Karnok, it is a third-generation library that supports various programming models for concurrency that exist for both Scala and Java.

There are a variety of libraries available nowadays (Rx, Spring, etc.) that make it possible to include reactive programming into your project using various techniques and frameworks.

Take a look into the reactive library : RXJava.

GitHub: RXJava

Let’s do a simple Hello World snippet as below.

import io.reactivex.rxjava3.core.*;
public class HelloWorld {
    public static void main(String[] args) {
        Flowable.just("Hello world").subscribe(System.out::println);
    }
}

Another reactive library is Project Reactor. It is based on reactive streams specification and focused on creating non-blocking applications on JVM.

6. Reactive Programming Benefits

Despite its complexity, understanding reactive programming may greatly simplify your job. In that case, how can Rx help while creating software?

Because it can handle large amounts of data fast, Reactive programming is useful to developers for boosting an app’s performance. These components make up Reactive Programming:

  • Improved adaptability
  • Capable of withstanding pressure and growing in size
  • Increased tolerance for setbacks
  • Conserve energy and materials
  • Not as covert
  • Extremely receptive

A lot of attention require to make the reactive programming modules as responsive as possible. Their response to users is both efficient and engaging.

As a result of its tidier structure and greater conciseness, Reactive Programming code is simpler to comprehend and scale. In this approach, it will be easier to make adjustments and updates. Such characteristics bring us to yet another benefit of Reactive Programming: it’s time-efficiency.

In addition to its other benefits, reactive programming provides more robust error handling. It may also be used to apply backpressure, which is a nice bonus. This implies the receiver can direct the publication’s data outflow. This method enables the service to prevent “out of memory” errors and keeps the user-provider traffic flowing smoothly.

7. When to Use Reactive Programming?

Reactive programming is an excellent solution for some sorts of high-load or multi-user applications:

  • Networking sites, conversations
  • Gaming
  • Audio and video application development

And to the preceding elements of any program type:

  • Code running on the server that offers out fully engaging UI components
  • Load balancing and proxy servers
  • Artificial intelligence, machine learning
  • Broadcasting data in real time

8. When Not to Use Reactive Programming?

Briefly said, do not attempt to pertain to Reactive Programming when it is unnecessary, such as when there is no “live” data, a heavy load, or a significant number of concurrent users that modify data.

9. General Significance of Reactive Programming

General Significance of Reactive Programming

Better Performance

Performance gains, thanks to the ability to quickly and reliably process massive data sets.

Dynamic UX

User experience (UX) is enhanced since it is possible to maintain a state in which the program remains reactive to its user.

Modified Updates

More understandable and predictable code makes it simpler to make changes and updates.

10. Summary

In this post, we’ve taken a high-level, all-encompassing look at the Reactive movement and placed it within the context of today’s business world. There are now several different Reactive libraries and frameworks being developed for the JVM. They have several similar characteristics, and are becoming compatible with one another because of Reactive Streams.

While it may take time and effort to fully grasp the notion and acquire Reactive Programming, the paradigm is immensely beneficial in the modern world. It has a lot of benefits that make development easier, boost app performance, help apps to remain responsive, and ultimately, make users happier. Because of its ability to tailor each user’s experience, user experience (UX) has quickly become a top priority for modern apps.

The post Why Do We Need Java Reactive Programming? appeared first on TatvaSoft Blog.

]]>
https://www.tatvasoft.com/blog/java-reactive-programming/feed/ 8
Java Lambda Expression https://www.tatvasoft.com/blog/java-lambda-expression/ https://www.tatvasoft.com/blog/java-lambda-expression/#respond Tue, 22 Sep 2020 09:16:55 +0000 https://www.tatvasoft.com/blog/?p=3279 Advancement in technology occurs every single day. Java Lambda Expressions is a new additional extension in Java 8. With domain-expertise and experience in Java development, we have prepared this insightful blog on the use of Lambda expressions with functional interfaces and instances that will make users well-versed with Java lambda expressions.

The post Java Lambda Expression appeared first on TatvaSoft Blog.

]]>
Advancement in technology occurs every single day. Lambda expression in Java is a new additional extension in Java 8. With domain-expertise and experience in Java, As Java development company  we have prepared this insightful blog on the use of Lambda expressions with functional interfaces and instances that will make users well-versed with Java lambda expressions.

We do not have to define the Lambda expression. It is an anonymous method that does not execute itself. It can only be implemented if you define a functional interface and run that method. Lambda can be considered as methods that are implemented in the body section of the method.

Lambda expression was one of the most requested features which were made available since Java SE 8. A Java Lambda expression is a function that does not belong to any class. Java lambda expressions are commonly used to implement simple event listeners.

These lambda expressions are effective methods to represent one method interface using an expression. With its multi-functional collection library, it is easy to iterate, filter, and extract data and implement it.

How can You Define What a Functional Interface is?

An interface that contains only one abstract method called functional interface. It shows only one functionality. In the latest version of Java 8, lambda expressions are used to implement functional interfaces.

Syntax

As given in definition, a functional interface can have only one abstract method, but it can have one or more default methods as well as static methods.

Java Lambda expression syntax,

(argument-list) -> {body}.

There are three components in Lambda expression,

  • The first component is surrounded by parentheses is an argument list, which can have none, one, or multiple arguments.
  • The second component is Arrow-Token which can be used to connect the list of arguments with the body of expression.
  • The third component is the method body, which comprises expressions and statements that are used for lambda expressions.

Before the Lambda expression, we were using anonymous interface implementations.

Without Lambda:

interface Square {

public void size();

}

public class LambdaExpressionExample {

	public static void main(String[] args) {

	int sideLength=2;

		Square s = new Square() {

			public void size() {

				System.out.println("All sides are "+ sideLength +" meter length.");

			}

		};

		s.size();

	}

}

Using Lambda Expression, we can replace some of the code in the above example as given below:

Square s = ()  {

	System.out.println("All sides are "+ sideLength +" meter length.");

};

As you can see in the code above, we do not have to create an anonymous object for the method in the functional interface.

Lambda expressions and anonymous interface implementations, both are the same still there are a few differences. One of the differences is that anonymous interface implementation has a member variable, but lambda expressions can’t have member variables.

Lambda Parameters

Since Java lambda expressions are just methods, lambda expressions can also take parameters just like methods. These parameters must be the same count and same data type as the parameters of the method in the single method interface.

Zero Parameter

  • If the matching method from the interface does not have any parameter then you can write a Lambda expression like,
() -> { System.out.println("method body"); };
  • If the method body has only one line then you can also emit curly braces.
() -> System.out.println("method body");

Single Parameter

  • If interface method has one parameter then Lambda expression will be like this,
(param) -> {System.out.println("One parameter: " + param);};
  • For one parameter, you can also omit parentheses,
param -> System.out.println("One parameter: " + param);

Multiple Parameter

  • If the method you match with your Java lambda expression takes multiple parameters, the parameters need to be listed in parentheses. Here is how that looks in Java code:
(p1, p2)  {

System.out.println("Multiple parameters: " + p1 + ", " + p2);

};

Accessible Variables

A Java lambda expression is capable of accessing variables declared outside the lambda function body under certain circumstances.

Java lambda expression can access the following types of variables:

  1. Local variables
  2. Instance variables
  3. Static variables

Local Variables

  • A Lambda expression can access the value of a local variable declared outside the lambda body if and only if the variable is “effectively final” or declared as final.
  • If you try to change the value of that variable the compiler would give you an error about the reference to it from inside the lambda body.

Effectively Final

  • It means that the variable is not declared as final but its value has never been changed once it is assigned.

Instance Variables

  • A Lambda expression can also access an instance variable. Java Developer can change the value of the instance variable even after its defined and the value will be changed inside the lambda as well.

Static Variables

  • A Lambda expression can also use static variables. Because a static variable is accessible from everywhere in a Java application. Static variable can be changed once it is used in Lamda expression by the Java developer.

Method References

As you saw until now, lambda expression calls another method using the parameters that passed to the lambda expression. There is a shorter way to express the method call.

For example,

MyInterface myInterface = (str) -> { System.out.println(str); };
  • You have seen a short way to represent this is,
    MyInterface myInterface = str -> System.out.println(str);
    
  • Now, you have a shorter way to represent method call in Lambda like this,
    MyInterface myInterface = System.out::println;
    
  • Here the double colon (::) is a signal to the Java compiler that this is a method reference. The method defined after the double colon is referred to as a method reference.
  • Whatever class or object that has the referenced method defines before the double colon.

Conclusion

Undoubtedly, there are many advantages of Lambda expressions that we came across in this elaborate blog such as it reduces lines of code, sequential and parallel execution support, passing behavior into methods, and higher efficiency.

In this article, we have learned about functional interfaces, using it, how one can write lambda expressions, and different types of ways to define lambda expressions using different parameters like zero, one, two, or more parameters. Then, we also learned various variables that are accessible from a local lambda expression, instance, and static variables. After this, we also found a shorter way to express lambda expression using the double colon (::) which is called as a method reference.

Overall, now we are well-versed with using lambda expressions. We can reduce code lines without creating anonymous objects. Using Lambda, we can also define methods in the functional interface that will reduce memory consumption and accelerate productivity.

More Post on Java:
Is AWS Lamda is server side component?
Microservices Implementation in Java

The post Java Lambda Expression appeared first on TatvaSoft Blog.

]]>
https://www.tatvasoft.com/blog/java-lambda-expression/feed/ 0
Top Java 10 Features https://www.tatvasoft.com/blog/top-10-java-10-feature-listing/ https://www.tatvasoft.com/blog/top-10-java-10-feature-listing/#comments Wed, 24 Oct 2018 12:46:38 +0000 https://www.tatvasoft.com/blog/?p=1995 Oracle announced a new version of Java which turned out to be the speediest one for its feature release of the Java SE platform, till now. This is the first release in the newest release schedule, where you get a new Java release after every six months.

The post Top Java 10 Features appeared first on TatvaSoft Blog.

]]>

Oracle announced a new version of Java which turned out to be the speediest one for its feature release of the Java SE platform, till now. This is the first release in the newest release schedule, where you get a new Java release after every six months. It has decided to promote Open JDK binaries as primary JDK 10 which reduces the hassle for the big companies to shuffle from the current system every time, a new version is enhanced in every java release. Some of the key highlights in the new java release include application class-data sharing, heap collection as well as local variable types. A few of the prominent new Java 10 features are listed below:

1. Local Variable Type Inference

It is one of the newest Java 10 features for developers. Type inference is Java compiler’s ability to look at each method invocation and corresponding declaration of local variables to determine the type argument or multiple arguments that make the invocation applicable. Local Variable meaning ‘var’ is not a keyword, but it is a reserved type name in the Java Language. So it cannot be used as a method, package, class or interface. Its uses are defined such as:

  • Limited only to Local Variable with an initializer
  • Indexes of enhanced for loops or indexes
  • Local declared in for loop

Let us walk through an example:

var numbers = List.of(1, 2, 3, 4, 5); // inferred value ArrayList<string>
// Index of Enhanced For Loop
for (var number : numbers) {
     System.out.println(number);
}
// Local variable declared in a loop
for (var i = 0; i < numbers.size(); i++) {
      System.out.println(numbers.get(i));
}
</string>

2. Parallel Full GC for G1

With the new Java 10 features updated now, source code isolation of different garbage collectors can be improvised with the coming of the new and most common Garbage Collector Interface. It emphasizes on providing better modularity to the internal GC code which in future, will help for adding full garbage collection without changing existing codebase. Also it helps in removing or maintaining the previous GC Parallel.

3. Additional Unicode Language –Tag Extensions

It will enhance the java.util.Locale and related APIs to implement additional Unicode extensions of BCP 47 language tags. This added the support for the below mentioned additional extensions –

  • cu (currency type)
  • fw (first day of the week)
  • rg (region override)
  • tz (time zone)

4. Thread – Local Handshake

A handshake operation is a callback that is executed for each Java Thread while that thread is in a safe point safe state. The callback is implemented by the VM thread while keeping the thread in a blocked state or by the thread itself. It allows executing a callback on threads without performing a global VM safe-point. It is possible and also cost-effective to stop individual threads and not just all threads or none.

5. Heap Allocation on Alternative Memory Devices

Applications such as in-memory databases and big data have an increasing demand for memory. Such applications could use NV-DIMM for the heap since NV-DIMMs has a larger capacity, at lower cost, in comparison to DRAM.Heap Allocation feature enhances the capability of Hotspot VM by allocating the Java object heap on an alternative memory device, such as an NV-DIMM as specified by the user. It also targets alternative memory devices that have the same semantics as a DRAM, including the semantics of atomic operations, and can be used instead of DRAM for the object heap to the existing application code without any change.

6. Root Certificates

Java 10 promotes Open JDK binaries as primary binaries for the ease of using the system without needing to update it frequently.

The cacerts Keystore will be inhabited with a kit of root certificates issued by the CAs of Oracle’s Java SE Root CA Program. Critical security components like TLS will run by default in OpenJDK builds moving forward.

To ensure the integrity and confidentiality, It comprises a default set of root Certification Authority (CA) certificates in the JDK 10 which makes sure that both Oracle JDK 10 & Open JDK binaries will function the same.

7. Application Class – Data sharing

While initiating JVM, it performs some preliminary steps, one of which is loading classes in memory. If there are multiple jars having several classes, then the lag in the first request is simply visible. There arises a problem with serverless architecture, where the boot time is critical. In order to carry forward the application startup time, Application class-data sharing is used that enables the bootstrap class loader to load classes that have been archived. It is to reduce footprint by sharing common class metadata across several Java processes.

8. Removal of the Native-Header Generation Tool – Java

It allows removing javah tool from JDK 10. It is not mandatory to remove – it is optional. The tool functionality of javad is added in JDK 8, which helps to generate native header files when compiling JNI code without using javah.

9. Consolidate the JDK Forest into a Single Repository

For a long time, for Java development, several repositories were utilized for the JDK forest codebase. Multiple repositories do provide several advantages, but it also comes with various operational downsides. It helps to combine the numerous repositories of the JDK forest into a single repository for streamlining the development process.

10. Experimental Java-Based JIT Compiler

Graal, as defined in Java 9, is an alternative to the JIT compiler which has been used to plugin to the JVM, meaning that the JIT compiler is not attached with JVM and can be dynamically plugged in or replaced with any other plugin. It also introduces Ahead of Time (AOT) compilation in java. It also supports the interpretation of the polyglot language. This feature enables the Java-based JIT compiler, Graal, to get used as an experimental JIT compiler on the Linux/x64 platform.

11. Time-Based Release Versioning

Time-based release versioning improves the version-string scheme of the Java SE Platform and the JDK 10, and similar versioning data, for today and upcoming release models.

Ending the Line

Overall, it seems that JDK 10 updates provide supportive new features to the java community. It also modifies or merges the features from the older version. By this enhancement, now Java developers have the privilege to code with less time complexity and efficiency. Yet, it also helps the developers to work less on some features and reduce the time complexity.

The post Top Java 10 Features appeared first on TatvaSoft Blog.

]]>
https://www.tatvasoft.com/blog/top-10-java-10-feature-listing/feed/ 7
Microservices Implementation in Java https://www.tatvasoft.com/blog/microservices-implementation-java/ https://www.tatvasoft.com/blog/microservices-implementation-java/#comments Tue, 27 Feb 2018 06:40:08 +0000 https://www.tatvasoft.com/blog/?p=1953 Microservices is a synonym for Service Oriented Architectural (SOA) style of constructing aggregation of many small loosely coupled services. When developing microservices with the Java programming language, you can use several microservices framework.

The post Microservices Implementation in Java appeared first on TatvaSoft Blog.

]]>
Microservices is a synonym for Service Oriented Architectural (SOA) style of constructing aggregation of many small loosely coupled services. When developing microservices with the Java programming language, you can use several microservices framework. Some of the frameworks are Spring Boot, Jersey, Dropwizard, Play Framework, and Restlet. DropWizard pulls together stable Java libraries in lightweight packages. We can also use them for our own applications. With the help of Restlet, developers can create fast and scalable web APIs that follows RESTful architecture pattern. In this document, we will implement a microservice “authenticate” with Spring Boot. Spring Boot is the most used and best Java Microservices framework since long.

The advantage of Spring Boot is that it has a vast infrastructure and has many spring boot projects working along. To create microservices with Spring Boot, you need to follow below mentioned 3 steps:

  • Setup new service
  • Expose the resource using RestController
  • Consume the service resource with RestTemplate

Here, we are going to create 3 different microservices in Java. First microservice is Discovery Server which is a Eureka server. Second microservice is Authentication Service which is Producer service and Third microservice is Consumer service which is discovery client. These microservices can find other microservices using its RestTemplate. Let’s start with developing these three microservices.

Developing Discovery Server

Service Discovery is used so that microservices can find each other. We use Eureka for our service discovery. Eureka, created by Netflix, provides service discovery with Spring Cloud. Folder Structure for Discovery server is as below:

folder structure

Maven Dependency:

<parent>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-parent</artifactid>
    <version>1.5.3.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupid>org.springframework.cloud</groupid>
        <artifactid>spring-cloud-starter</artifactid>
    </dependency>
    <dependency> <!-- Eureka registration server -->
        <groupid>org.springframework.cloud</groupid>
        <artifactid>spring-cloud-starter-eureka-server</artifactid>
    </dependency>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
</dependencies>
<dependencymanagement>
    <dependencies>
        <dependency>
            <groupid>org.springframework.cloud</groupid>
            <artifactid>spring-cloud-dependencies</artifactid>
            <version>Camden.SR5</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencymanagement>

Application.yml:

eureka: # Configure this Discovery Server
    instance:
        hostname: localhost
    client: 
        registerWithEureka: false
        fetchRegistry: false
server: # HTTP (Tomcat) port
    port: 9000

To run Eureka registry service is easy, just define @EnableEurekaServer annotation to spring boot application.

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(DiscoveryServerApplication.class, args);
    }
}

After running this microservice, following output is available on localhost:9000:

Microservices output

Here in the application section of the image, there is no instance currently available with Eureka. After running Producer and Consumer microservice, we will able to see the instances in the Application section.

Developing Authentication Service

In this, we will create Login and Registration methods. We will use Spring Data JPA for querying MySQL database using method name convention. You can learn spring data JPA from this site: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/. Also in this, we will be hashing the password using Spring Security’s BCrypt algorithm. Folder Structure for Authentication service is as below:

Authentication service

Maven Dependency:

<dependencies>
    <dependency>
        <groupid>org.springframework.cloud</groupid>
        <artifactid>spring-cloud-starter</artifactid>
    </dependency>
    <dependency>
        <groupid>org.springframework.cloud</groupid>
        <artifactid>spring-cloud-starter-eureka</artifactid>
    </dependency>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-data-jpa</artifactid>
    </dependency>
    <dependency>
        <groupid>mysql</groupid>
        <artifactid>mysql-connector-java</artifactid>
    </dependency>
</dependencies>

Application.yml:

spring: # Service registers under this name
    application:
        name: authentication-service
    datasource: # MySql credentials
        url: jdbc:mysql://127.0.0.1:3306/test
        username: root
        password: root
    jpa: # JPA support
        show-sql: true
        hibernate:
            ddl-auto: validate
            use-new-id-generator-mappings: false
        properties:
            hibernate:
            dialect: org.hibernate.dialect.MySQLDialect
eureka: # Discovery Server Access
    client:
        serviceUrl:
            defaultZone: http://localhost:9000/eureka/
server: # HTTP Server (Tomcat) Port
    port: 9001

To define this microservice as Discovery Client, we need to include @EnableDiscoveryClient annotation to application.

@SpringBootApplication
@EnableDiscoveryClient
public class AuthenticationClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(AuthenticationClientApplication.class, args);
    }
}

We will create AuthenticationRepository to querying the database using JPA. To expose Authentication service, we use RestController. In the controller, @CrossOrigin annotation is used to pass data or get data from cross platforms like Angular.

@RestController
@CrossOrigin
public class AuthenticationController {
    @Autowired
    private AuthenticationRepository repo;
    @RequestMapping("/api/getUsers")
    public @ResponseBody List<userauthenticationbean> getUsers() {
        return repo.findAll();
    }
    @RequestMapping(value = "/api/addUser",method = RequestMethod.POST)
    public @ResponseBody UserAuthenticationBean addStudent(@RequestBody UserAuthenticationBean user) {   // Hashing the password using BCrypt of Spring Security 
        String hashed_password = BCrypt.hashpw( user.getPassword(), BCrypt.gensalt(12) ); 
        UserAuthenticationBean newuser = new UserAuthenticationBean();
        newuser.setUserName(user.getUserName());
        newuser.setPassword(hashed_password);
        return repo.save(newuser);
    }
    @RequestMapping(value = "/api/getUser" ,method = RequestMethod.POST)
    public @ResponseBody UserAuthenticationBean getByUser(@RequestBody UserAuthenticationBean user) {
        UserAuthenticationBean userget = repo.findByUserName(user.getUserName());
        // Comparing Hashed password with given password
        If ( BCrypt.checkpw( user.getPassword(), userget.getPassword() ) ){
            return userget;
        } return null;
    } 
}
</userauthenticationbean>

After running this microservice, you can fire rest call to this service on localhost:9001. Also, instance of this service gets registered in eureka server which is already running on localhost:9000.

Developing Consumer Service with Spring Cloud

In this service, we will use RestTemplate to consume the remote service resource. Also we use Spring Cloud’s Netflix support for load balancing. Load balancing is used to decide which service instance to use. Netflix Ribbon provides several algorithms for client-side load balancing. Folder Structure for Consumer service is as below:

Consumer service

Maven Dependency:

<dependencies>
    <dependency>
        <groupid>org.springframework.cloud</groupid>
        <artifactid>spring-cloud-starter-eureka</artifactid>
    </dependency>
    <dependency> <!-- Netflix Ribbon used for Load Balancing -->
        <groupid>org.springframework.cloud</groupid>
        <artifactid>spring-cloud-starter-ribbon</artifactid>
    </dependency>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
</dependencies>

Application.yml:

spring: # Service registers under this name
    application:
        name: consumer-service
eureka: # Discovery Server Access
    client:
        serviceUrl:
            defaultZone: http://localhost:9000/eureka/
server: # HTTP Server (Tomcat) Port
    port: 8081

You need to include RemoteRepository bean and RestTemplate bean in main application, so that this microservice can consume other microservices.

@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerServiceApplication {
 
    public static final String AUTHENTICATION_SERVICE_URL = "http://AUTHENTICATION-SERVICE";
 
    public static void main(String[] args) {
        SpringApplication.run(ConsumerServiceApplication.class, args);
    }
 
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
 
    @Bean
    public AuthenticationRepository authenticationRepository(){
        return new RemoteAuthenticationRepository(AUTHENTICATION_SERVICE_URL);
    }
}

RemoteRepository will pass the HTTP request to the given Service URL and get the response from the remote service.

public class RemoteAuthenticationRepository implements AuthenticationRepository {
    @Autowired
    @LoadBalanced
    protected RestTemplate restTemplate;
    protected String serviceUrl;
 
    public RemoteAuthenticationRepository(String serviceUrl) {
        this.serviceUrl = serviceUrl.startsWith("http") ? serviceUrl : "http://" + serviceUrl;
    }
    @Override
    public List<userauthenticationbean> findAll() {
        UserAuthenticationBean[] users = restTemplate.getForObject(serviceUrl+"/api/getUsers", UserAuthenticationBean[].class);
        return Arrays.asList(users);
    }
 
    @Override
    public UserAuthenticationBean findByUserNameAndPassword(String userName, String password) {
        UserAuthenticationBean user= new UserAuthenticationBean(); 
        user.setPassword(password);
        user.setUserName(userName);
        return restTemplate.postForObject(serviceUrl + "/api/getUser",user,UserAuthenticationBean.class);
    }
 
    @Override
    public UserAuthenticationBean save(UserAuthenticationBean user) {
        return restTemplate.postForObject(serviceUrl + "/api/addUser", user, UserAuthenticationBean.class);
    }
}
</userauthenticationbean>

After running this service on localhost:8081, you can fire HTTP request from client side and request to this service will be passed to producer microservice, in our scenario Authentication service. Also, you will be able to see instance of this microservice in Eureka server on localhost:9000 as below:

Microservice in Eureka server

Advantages of Microservices

Is it fair not to know the advantages of Microservices when we have discussed almost everything about it? Ideally not. Microservices are well-suited to agile development techniques and are designed to meet the growing demands of market for a more fluid information flow. It has the capability to offer many advantages such as

The deployment of Microservices works independently

Each microservice can be launched independently as needed, allowing for faster app upgrades and ongoing improvement. Specific development teams might be assigned to specific microservices, allowing them to concentrate completely on one service or functionality. As a result, teams may operate independently without having to worry about what’s going on in the rest of the programme.

Easily Scale an App with Microservices Architecture

It’s easier to scale an app with microservices architecture as demand grows. Rather than growing a full app, you may focus on the most important microservices. Scaling is also faster and more cost-effective as a result of this.

Microservices reduce downtime

If a single microservice fails, you may isolate it from the rest of the programme, preventing cascading failures that would cause it to crash. Because of this fault isolation, even if one of your important application’s modules fails, it can continue to function.

Coding is easier with micro codebase

Microservices have minimal codebases, which makes them easier to manage and deploy. It’s also a lot easier to keep the code clean and assign responsibility for certain services to teams.

Disadvantages of Microservices

While we know that Microservices are a blessing for the developer community, it would be incorrect to ignore the disadvantages of Microservices. This is for the users to know and understand the cons as well before implying within their business.

Microservices increase the Level of Complexity

Microservices allow you to use any technology, troubleshooting may become more difficult. It’s significantly more difficult to trace failures from one microservice to the next than it is in a single traditional application. This is especially true when each service has its own language, platform, monitoring tool, logging system, and other features. Performance issues can also be more difficult to resolve.

Adversely affect the development culture

While using microservices, businesses need to reorganize and distribute throughout all the services they’re working with because your team structure and dynamics have changed. This will not only take a lot of time and effort to figure out who should be where, but it may also create conflict if certain people are unhappy with the change or not. The leaders must grasp the changes and potential pain areas and then there is a great chance to improve the success of your organization.

Java Microservices need DevOps

Finally, microservices teams must work in highly automated environments, as some firms will have dozens of moving parts, which is impossible to manage manually. This will necessitate the adoption and utilization of DevOps tools such as Continuous Integration/Continuous Delivery (CI/CD) and distributed logging, tracing, monitoring, and visualization services.

Conclusion

To summarize, we understand about using microservices with Spring Boot Project. Also we learned some information on Eureka server and Netflix Ribbon for discovery service and Load balancing. You can learn more about microservices with spring from site: https://spring.io/blog/2015/07/14/microservices-with-spring

The post Microservices Implementation in Java appeared first on TatvaSoft Blog.

]]>
https://www.tatvasoft.com/blog/microservices-implementation-java/feed/ 9
Spring Data JPA for Abstraction of Queries https://www.tatvasoft.com/blog/spring-data-jpa-for-abstraction-of-queries/ https://www.tatvasoft.com/blog/spring-data-jpa-for-abstraction-of-queries/#respond Tue, 06 Feb 2018 06:31:00 +0000 https://www.tatvasoft.com/blog/?p=8941 Developers use boilerplate of code to execute even simple queries. Also pagination and auditing takes long lines of code and efforts. But when developer uses Spring Data JPA, they can execute query by creating methods with the use of method name convention. And Spring will provide the implementation of that method automatically.

The post Spring Data JPA for Abstraction of Queries appeared first on TatvaSoft Blog.

]]>
Developers use boilerplate of code to execute even simple queries. Also pagination and auditing takes long lines of code and efforts. But when developer uses Spring Data JPA, they can execute query by creating methods with the use of method name convention. And Spring will provide the implementation of that method automatically.

Spring Data JPA for Abstraction of Queries

Spring Data JPA is not actually a JPA provider like Hibernate, Jboss, EclipseLink and DataNucleus. It is a library or framework. And it adds one layer of abstraction on top of JPA provider. Using Spring in Java development, outcomes with a newer and elegant way of data access.

Feature Listing

  • Can build repositories by extending any Spring Data Repository.
  • Use any inbuilt CRUD methods provided by CRUDRepository.
  • Create Methods using Method name convention or create method providing @Query annotated query.
  • Pagination, Slicing, Sorting and Auditing support
  • XML based entity mapping support
  • Specification<T> and QueryDsl support

JPA Specifies support For:

  • JPQL: It is a string-based query language.
  • Criteria Query: It uses Criteria to execute JPQL query. It provides API support for re-factoring of classes.
  • Native Query: To execute SQL query from JPA, set native query flag to true.
  • It also provides support for RDBMS Stored Procedures.

Interfaces provided by Spring Data JPA:

  • JPA specific repository interface is JpaRepository<T, ID extends Serializable> It uses combination of methods declared by CRUDRepository<T, Serializable>, PaginationAndSortingRepository<T, Serializable>, Repository<T, Serializable>.
  • Not JPA specific repository interface is JpaSpecificationExecutor<T> It uses methods which are already defined in Specification<T> objects. Criteria API is used in Specification<T> method to retrieve entities from the database.

How to use Spring Data JPA:

  • Create own repository interface and extend any repository interfaces provided by Spring Data.Ex:
    • public interface UserJPARepository extends JpaRepository&lt;UserJPA, Long&gt;{}

      – Here UserJPARepository is new interface that developer creates which extends JpaRepository and here UserJPA is the entity on which queries are going to perform.

  • If needed, create any Custom method using @Query annotation or using Method name convention.Ex:
    • UserJPA findByEmail (String email);

      – Here, findByEmail method will execute “select * from table_name where email = ‘given_email_from_method_Patameter’ “

    • Page findAll(Pageable pageable);
    • List findByBirthDateBetween(Date startDate, Date endDate);
    • List findByAgeLessThan(int age);
    • List findByAddress_PinCode(int pinCode);

      – Here, findByAddress_PinCode method will execute “SELECT p FROM UserJPA p LEFT JOIN p.address a WHERE a.pinCode= :pinCode“. It will fire a join query and pass parameter which is defined in joined table.

    • @Nullable List findByFirstNameNotLike(Nullable String firstName);

      – It will return null in case of no result. Also it will accept null value for firstName.

    • Optional findOptioanlByEmail(String email);

      – It will return Optional.empty() in case of no result and even throw an IllegalArgumentException if email value is null.

    • Slice findTop100ByLastName (String lastName, Pageable page);

      – Top and First in the query will return limited (here 100) Number of distinct records. Slice will generate limitation per page. For ex: If there are 10 records per page then for 100 records 10 pages getscreated.

    • @Query ("SELECT u FROM UserJPA u WHERE u.age &lt; (SELECT count(n.addressId) FROM AddressJPA n)")
      public List findByInnerQuery();
    • @Query ("select * from user_jpa", nativeQuery=true)
      public List findBySQLQuery();

      – Here, using nativeQuery=true flag provides executing query with SQL syntax.

  • To use this repository, inject the repository interface to another component.Ex:
    • @Autowired
      private UserRepository repo; // ingesting repo to another class
    • repo.findAll(); // inbuilt query
    • repo.save(); // inbuilt query
    • repo. findAll(new PageRequest(0,10)); // custom query

      – Here, 0 is number of page (1st page in array) and 10 is number of records per page

    • repo.findByAgeLessThan(50); // custom query

Spring Data JPA vs Hibernate Coding:

For CRUD operation using Spring Data JPA, developer has no need to create implementation of methods. Ex:

  • repo.findAll(); // inbuilt query

    This will list out all the records from tables. Where as if developer using Hiberante, then for repo.findAll() method, they have to write some lines of code like:

  • Session session = this.sessionFactory.getCurrentSession();
    List listUsers = session.createQuery("from UserJPA").list();
    return listUsers;

Ex:

  • repo.findByAgeLessThan(int age); // custom query

    This will list out all the records from tables. Where as if developer using Hiberante, then for repo.findAll () method, they have to write some lines of code like:

  • Session session = this.sessionFactory.getCurrentSession();
    Query query = session.createQuery("from UserJPA where age &lt; :age");
    query.setParameter("age", 50);
    List listUsers = query.list();
    return listUsers;

Transactionality:

  • With transactions configured, you can configure a bean with @Transactional either at the method level or class level.
  • Developer use @Transactional annotation to make sure that transaction is running.
  • Reading methods like findAll() or findOne() are using @Transactional(readOnly=true) which triggers performance optimizations inside the persistence provider as well as on the database level.
  • @Transactional(timeout=10)
    public List findAll();

    This will cause the findAll() method to be executed with a timeout of 10 seconds.

  • @Transactional(isolation=Isolation.SERIALIZABLE)

    It will protect against dirty, non-repeatable reads.

  • @Transactional(readOnly=true, propogation = Propogation.SUPPORTS)

    From non-transactional context, using this annotation read-only flag gets ignored and transaction won’t get created.

QueryDsl:

QueryDsl is a framework which creates SQL-like queries via its API. To use QueryDsl, extends QueryDslPredicateExecuter in repository. Ex:

  • Predicate pre = firstName.equalsIgnoreCase(“abc”).and(user.lastName.startsWithIgnoreCase(“bcd”));
    repo.findAll(pre);

Specification:

To extend specification, extend JpaSpecificationExecutor. Using this will allow you to use specification in methods. Specification method uses criteria query in the logic. Ex:

  • List findAll(Specification spec);

Ex:

  • Specification isAdmin(){ //predicate(){ //method_logic }}
    repo.findAll(isAdmin());

    – This method will find all the records that matches with such specifications.

Auditing:

Auditing means keeping track of who created or changed an entity And the point of time this changes happened. JPA provides @CreatedBy and @LastModifiedBy annotation to define who created and modified the entity. Also provides @CreatedDate and @LastModifiedDate to define time of occurrence. Ex:

  • class Customer {
    @CreatedBy
    private UserJPA user;
    @CreatedDate
    private DateTime createdDate;
    }

The post Spring Data JPA for Abstraction of Queries appeared first on TatvaSoft Blog.

]]>
https://www.tatvasoft.com/blog/spring-data-jpa-for-abstraction-of-queries/feed/ 0
JAVA 9 Features https://www.tatvasoft.com/blog/java-9-feature-listing/ https://www.tatvasoft.com/blog/java-9-feature-listing/#comments Mon, 04 Dec 2017 12:28:48 +0000 https://www.tatvasoft.com/blog/?p=1974 After nearly 3 years of disagreements and agreements on controversial Project Jigsaw, Java 9—formally, Java Platform Standard Edition version 9 is finally here. Java SE 9 has various key architectural as well as component changes, making SE 9, the major feature release for Java Platform.

The post JAVA 9 Features appeared first on TatvaSoft Blog.

]]>
1. Java 9 Features list

After nearly 3 years of disagreements and agreements on controversial Project Jigsaw, Java 9—formally, Java Platform Standard Edition version 9 is finally here. Java SE 9 has various key architectural as well as component changes, making SE 9, the major feature release for Java Platform. The following are mentioned some of the key features and enhancements of Java 9:

Java 9 Features

1.1 Module System (Jigsaw Project)

This is a new type of Java programing component that is useful for collecting Java code. Though the most significant feature of Java 9 is the Module System, still it is very controversial. It is released as a part of Jigsaw Project by Oracle Corporation to ease the woes of Java SE previous versions. Following features are part of the Jigsaw Project:

  • Modular JDK
  • Modular Java Source Code
  • Modular Run-time Images
  • Encapsulate Java Internal APIs
  • Java Platform Module System

As in Java 9, JDK, JRE, JARs etc. are divided into smaller modules, so java developers can implement only those modules that are demanded to develop a particular application. In addition, Module system provides ease of Testing and Maintainability, support to better Performance, support for strong Encapsulation, support to less coupling between components, support to Single Responsibility Principle (SRP) and restricts access to Internal Non-critical APIs.

1.2 JDK 9 Folder Structure:

JDK 9 folder structure, unlike JDK 8 folder structure, doesn’t possess JRE folder. JRE is separated into a different folder named ‘jmods’, that contains a set of Java 9 modules and is available at ${JAVA_HOME}/jmods. ‘jmods’ which has approximately 95 modules collectively known as “JDK Modules”.

1.3 Java SE 9 Module:

Java 9 module is a self-explanatory collection of the following main components:

  • One Module
  • Module Name
  • Module Descriptor
  • Set of packages
  • Set of types and resources

In Java 9, JDK jars and Java SE Specifications are separated into two sets of modules – All JDK modules start with “jdk”, while all Java SE specifications modules start with “java”. Java SE 9 has a “java.base” module commonly known as base module and acts as the heart of all Java 9 modules (all JDK modules and User-defined modules).

Developers can create their own modules as shown below:

module com.foo.bar { }

Here, ‘module’ is used to create a simple module.

Java 9 application with added component Modules can be understood from the below figure:

java9_app

1.4 Jshell (Java 9 REPL)

Java 9 features the Read-Eval-Print-Loop (REPL) tool most commonly known as Jshell. Java 9’s REPL feature interactively evaluates declarative statements and expressions. With this, developers can receive feedback for programs before compilation, just by adding few lines of code. It does not require any IDEs or Editors to execute simple Java development services.

It is used to execute and test any Java Constructs like class, interface, enum, object, statements, etc. very efficiently and quickly.

D:\>jshell
|  Welcome to JShell -- Version 9-ea
|  For an introduction type: /help intro
jshell> int a = 10
a ==> 10
jshell> System.out.println("a value = " + a )
a value = 10

1.5 Reactive Streams

Reactive programming has become very popular in application development with technologies like Scala,Play, Akka, etc. In Java 9, new Reactive Streams API are introduced to achieve similar features as of reactive programming.

Java SE 9 Reactive Streams API is a Publish/ Subscribe Framework used to implement Asynchronous, Scalable and Parallel applications easily. Java SE 9 has introduced the following APIs to develop Reactive Streams in Java-based applications:

  • java.util.concurrent.Flow
  • java.util.concurrent.Flow.Publisher
  • java.util.concurrent.Flow.Subscriber
  • java.util.concurrent.Flow.Processor

1.6 Multi-Resolution Images

A new multi-resolution image API, defined in java.awt.image package, allows a set of images with different resolutions to be wrapped up into a single multi-resolution image. Below mentioned basic operations can be performed on a multi-resolution image:

  • To retrieve a resolution-specific image variant based on a given DPI metric and set of image transformations, and
  • To retrieve all of the variants in the image

Apart from these operations, a multi-resolution image will behave alike an ordinary image. The java.awt.Graphics class will retrieve the necessary variant from a multi-resolution image based on the current display DPI metric and any applied transformations.

1.7 Private Methods in Interface

In Java SE 8, developers were allowed to write method implementation in interfaces by using Default and Static methods. But this feature led to code redundancy. To remove the code redundancy, one way was to extract common code in a public method which led to a threat of exposing code to other modules and clients directly.

However, we cannot perform private interface methods. From Java SE 9 onwards, we can address private and private static void display card details in an interface practicing the ‘private’ keyword.

Java SE 9 introduced a new feature to interfaces to give answer to the raised issues – Private methods in interface. Interfaces can have any of the following members:

  • Constant Variables
  • Abstract Methods
  • Default Methods
  • Static Methods
  • Private Methods
  • Private Static Methods

Example:-

public interface DBLogging{
      String MONGO_DB_NAME = "ABC_Mongo_Datastore";
      String NEO4J_DB_NAME = "ABC_Neo4J_Datastore";
      String CASSANDRA_DB_NAME = "ABC_Cassandra_Datastore";
      default void logInfo(String message){
        log(message, "INFO")
      }
      default void logWarn(String message){
        log(message, "WARN")
      }
      default void logError(String message){
         log(message, "ERROR")
      }
      default void logFatal(String message){
         log(message, "FATAL")
      }
      private void log(String message, String msgPrefix){
         Step1: Connect to DataStore
         Setp2: Log Message with Prefix and styles etc.
         Setp3: Close the DataStore connection  
      }
      // Any other abstract methods
   }

Here, redundant code has been extracted into a common private method so that API Clients cannot see the crucial code.

1.8 Process API

In the Process API, Oracle team added a couple of new classes and methods to ease the controlling and managing of OS processes. Two new interfaces added in Process API are:

  • java.lang.ProcessHandle
  • java.lang.ProcessHandle.Info

Process API example

ProcessHandle currentProcess = ProcessHandle.current();
System.out.println("Current Process Id: = " + currentProcess.getPid());

Some of the information, developers can now obtain from Process instance which includes:

  • Whether the process supports normal termination (i.e. any of the “non-forcible” kill signals in Linux)
  • The process ID (i.e. the “pid”)
  • A handle to the current process
  • A handle to the parent process, if one exists
  • A stream of handles to the direct children of the process
  • A stream of handles to the descendants (direct children, their children, and so on recursively)
  • A stream of handles to all processes visible to the current process
  • Process metadata such as the full command line, arguments, start instant, owning user, and total CPU duration

1.9 Try-with Resources

Java SE 9 has added a few improvements in Java SE 7’s new exception handling construct: Try-With-Resources, to overcome the flaws in Java SE 7.

Try-With-Resources Example-Java SE 7:

void testARM_Before_Java9() throws IOException{
 BufferedReader reader1 = new BufferedReader(new FileReader("test.txt"));
 try (BufferedReader reader2 = reader1) {
   System.out.println(reader2.readLine());
 }
}

Here, a utility method which creates a BufferedReader object to read the content of a file is created. If the above code snippet is observed, even though there is reader1 referring to the BufferedReader object, a duplicate “reader2” BufferedReader object has been created to use it in Try-With-Resources. It is one small bug or issue in Java SE 7 or 8 versions.

In Java SE 9 to overcome the above mentioned issue, if there is a resource already declared outside the Try-With-Resource Statement as final or effectively final, so now there is No need to declare a local variable. Previously created variable can be used within Try-With-Resource Statement without any issues as shown below:

void testARM_Java9() throws IOException{
 BufferedReader reader1 = new BufferedReader(new FileReader("test.txt"));
 try (reader1) {
   System.out.println(reader1.readLine());
 }
}

1.10 Diamond Operator Extension

Java SE 9 has provided extension to the Java SE 7 feature with Diamond Operators, in order to remove the limitations and issues with Anonymous Inner Classes. Following code snippet shows the limitation of diamond operator with Anonymous Inner classes in Java SE 7:

public abstract class MyHandler<t>{
    //constructor, getter, setter..
    abstract void handle();
}
// valid code
MyHandler<integer> intHandler = new MyHandler<integer>(1) { 
public void handle() {
                // handling code...
            }
 };
//Invalid in Java SE 7 & 8
MyHandler<integer> intHandler = new MyHandler<>(10) { // Anonymous Class };
MyHandler<!--?--> handler = new MyHandler<>(""One hundred") { // Anonymous Class };
</integer></integer></integer></t>

The above code throws compilation error in Java SE 7 & 8 while it runs without compilation error in Java SE 9 due to the Diamond Operator Extension introduced.

1.11 Unified JVM Logging

Java 9 came up with a unified logging architecture (JEP 158) that pipes a lot of messages that the JVM generates through the same mechanism, which can be configured with the -Xlog option especially for complicated Java Software Development.

Java’s new version includes a common logging system and logging framework for all elements of the JVM.

This gives uniform access to log messages from different subsystems such as class loading, threading, garbage collector, module system, or interaction with the underlying operating system.

By simply executing java -Xlog, appending -version gives the below output:

$ java -Xlog -version

# truncated a few messages

> [0.002s][info][os ] HotSpot is running with glibc 2.23, NPTL 2.23

# truncated a few messages

It shows how long the JVM has been running (2 ms), the message’s log level (info), its tags (only os), and the actual message.

1.12 SafeVarargs Scope Extension

Java 7 introduced the SafeVarargs annotation type for asserting that the bodies of annotated final or static methods, or constructors don’t perform potentially unsafe operations on their varargs (variable number of arguments) parameters. Java 9 expands this capability to also include private methods.

SafeVarargs must be used with methods that can’t be overridden because an overriding method could violate its superclass method’s @SafeVarargs annotation by performing an unsafe operation. Static, final, and private methods, and constructors can’t be overridden, so they are used with SafeVarargs.

1.13 HTTP 2 client

New HTTP 2 Client API to support HTTP/2 protocol and WebSocket features has been introduced in Java SE 9. As Legacy HTTP Client API has several issues like supporting HTTP/1.1 protocol and doesn’t help HTTP/2 protocol and WebSocket, it works only in “Blocking mode” and has a lot of performance issues. Now they have a new API HTTP 2 Client that is beneath the “java.net.http” package. This HttpURLConnection API is being replaced with new HTTP client.

This API is being introduced under the “java.net.http” package. It supports both HTTP/1.1 and HTTP/2 protocols and both Synchronous (Blocking Mode) and Asynchronous Modes. The Asynchronous Mode is supported using WebSocket API.

HTTP 2 Client Example

jshell> import java.net.http.*
jshell> import static java.net.http.HttpRequest.*
jshell> import static java.net.http.HttpResponse.*
jshell> URI uri = new URI("http://test/2016/05/java-news.html")
uri ==> http://test/2016/05/java-news.html
jshell> HttpResponse response = HttpRequest.create(uri).body(noBody()).GET().response()
response ==> java.net.http.HttpResponseImpl@79efed2d
jshell> System.out.println("Response was " + response.body(asString()))

1.14 HTML 5 Javadoc

Javadoc is the tool that can generate API documentation in HTML format. In the previous version of JDK, it’s HTML 4.01 – an old standard. JDK 9 Javadoc now supports generating HTML5 markup, improves search capability and Doclint.

-Xdoclint enables recommended checks for issues in Javadoc comments: bad references, lack of accessibility, missing comments, syntax error and missing HTML tags. By default, -Xdoclint is enabled. We can disable it by -Xdoclint:none.

1.15 Miscellaneous Java SE 9 features:

Some of the miscellaneous features of Java SE 9, equally important as the key features, are GC (Garbage Collector) Improvements, Stack-Walking API, Filter Incoming Serialization Data, Deprecate the Applet API, Indify String Concatenation, Enhanced Method Handles, Java Platform Logging API and Service, Compact Strings, Parser API for Nashorn, Javadoc Search, etc.

Stream API Improvements:

In Java SE 9, Oracle Corp. has combined four beneficial new methods to java.util.Stream interface. As a Stream interface, all these new execution methods are essential methods.

Java Collection Factory Methods:

Factory methods are specific kinds of static methods that are applied to produce unmodifiable instances of collections. It suggests that we can utilize these methods to build a list, set, and map of a small number of factors.

Remove Launch-Time JRE Version Selection:

Java 9 has excluded JRE (Java Runtime Environment) version choice at launch time. Now, the latest application has its active installer that additionally contains methods to handle the JRE. That’s why the JRE version choice has been eliminated.

Prepare JavaFX UI Controls and CSS APIs for Modularization:

Java involves public APIs for CSS functionality and JavaFX UI controllers. These functionalities were earlier obtainable only through internal packages, but now it is available because of the modular method.

XML Catalogs:

Standard XML catalog API is computed which helps the company for the Advancement of OASIS XML Catalogs version 1.1.

TIFF Image I/O:

TIFF (Tag Image File Format) is combined for reading and writing as a criterion. It is determined in the package javax.imageio.

Segmented Code Cache:

Code cache is split into different segments. Each segment is a selected code and advances performance and facilitates extensibility.

Filter Incoming Serialization Data:

It supports filtering the date of an incoming stream of object-serialization data to enhance both robustness and safety. Object-serialization clients implement can confirm their input more easily, and transported Remote Method Invocation (RMI) objects can prove invocation cases more easily.

Java 9 Control Panel:

Java control panel is practised to manage Java applications that are installed in the browser. This control panel controls the environments that manage Java applications installed in a browser.

Anonymous Classes Improvement:

Java 9 launched a new feature that enables us to practice diamond operators with an anonymous inner class. Practiscing the diamond with anonymous classes was not supported in Java 7.

OCSP Stapling for TLS:

OCSP (Online Certificate Status Protocol) benefits the server in a TLS link to review for a revoked X.509 certificate repeal.

UTF-8 Properties Files:

The UTF-8 is a convenient method to describe non-Latin characters. The new version of java contains properties files in UTF-8 encoding. In newer versions, ISO-8859-1 encoding was practiced when loading property resource bundles.

CLDR Locale Data Enabled by Default:

CLDR (Common Locale Data Repository) describes the locale data produced by the Unicode CLDR project. It was added in JDK 8 and now default in JDK 9.

Parser API for Nashorn:

Java combined Parser API which enables users to Enable applications, in server-side framework, special IDEs. It can be practiced to parse ECMAScript code from a series, URL, or file with systems of Parser class.

Validate JVM Command-Line Flag Arguments:

Java approves cases to all numeric JVM command-line flags to evade failure. If arguments are wrong or out-of-range, it presents an appropriate error message.

BeanInfo Annotations:

The @beaninfo Javadoc tag is substituted with the explanation types JavaBean, BeanProperty, and SwingContainer. We can practice these corresponding feature attributes immediately in the Bean class.

2. Java SE 9 Deprecated and Removed Features:

The main and foremost amongst them is Applet API which is deprecated as the security-conscious browser makers have been removing support for Java browser plug-ins. Developers are now headed towards alternatives such as Java Web Start, for launching applications from a browser, or installable applications. The appletviewer tool has been deprecated as well.

Concurrent Mark Sweep (CMS) garbage collector is also deprecated with the intention to speed up the development of other garbage collectors in the HotSpot virtual machine. The low-pause G1 garbage collector is intended to be a long-term replacement for CMS.

Java SE 9 excludes Java warnings on import statements to make large code bases clean of lint warnings.

Java SE 9 removes the ability to select the JRE at launch time via the Multiple JRE feature. Also the JVM TI (Tool Interface) hprof (Heap Profiling) agent and the jhat tool are removed as well.

3. End of its line

Oracle Corporation recently revealed that the Java SE 9 is the last of its kind, in terms of the designation and the time elapsed between major Java version releases. After that, the Java developers team has planned to have a six-month release cadence, the next major version is expected to be called Java 18.3, due in March 2018, followed by Java 18.9 six months later.

JDK 9 will not be a long-term support release instead the next long-term support release would be Java 18.9.

The post JAVA 9 Features appeared first on TatvaSoft Blog.

]]>
https://www.tatvasoft.com/blog/java-9-feature-listing/feed/ 6
Java 8 Features – Unleashed https://www.tatvasoft.com/blog/java-8-features-unleashed/ https://www.tatvasoft.com/blog/java-8-features-unleashed/#respond Fri, 09 Jun 2017 13:15:36 +0000 https://www.tatvasoft.com/blog/?p=2021 Java is the programming language used by millions of developers and numerous for their business solutions. With the Java 8 release, Java contributed in support for functional programming, enhancement of JavaScript engine, outstanding APIs for date time manipulation, new streaming API, etc.

The post Java 8 Features – Unleashed appeared first on TatvaSoft Blog.

]]>
Java is the programming language used by millions of developers and numerous for their business solutions. With the Java 8 release, Java contributed in support for functional programming, enhancement of JavaScript engine, outstanding APIs for date time manipulation, new streaming API, etc. There are dozens of notable and valuable features in Java 8, but the most significant features are discussed.

Out of all features, some are very talked about (booming) amongst developers, while few are not talked about (quiet) features.

Booming Java 8 Features

Booming Java 8 Features

1. Lambda Expressions

As per Java developer’s perspective, Lambda expression is one of the significant add-on features to the language. This extended feature brought Java App Development to the forefront of functional programming, just like other functional JVM-based languages – Scala and Clojure. A lambda expression is a function used to create delegates or expression tree types. Using lambda expressions, developers can code local functions which can be passed as arguments or returned as the value of function calls as lambdas are integrated in core language libraries.  Below example shows snippet of with and without lambda expressions. It mainly represents the difference in function calling ways

//without lambda, Drawable implementation using anonymous class 
Drawable d=new Drawable(){ 
public void draw(){System.out.println("Drawing"+width);} 
}
//with lambda 
Drawable d2=()->{  
System.out.println("Drawing"+width); 
};

2. Concurrent Accumulators

In Java based solutions, it is a very common scenario to use numeric counters which are accessed by multiple threads. In earlier Java versions it was difficult to modify the counter values. Java 8 resolved this issue with its concurrent accumulator classes, where the value can be increased/ decreased effectively in a thread safe method. Some concurrent API enhancements are mentioned as follows:

  • ConcurrentHashMap – compute(), forEach(), forEachEntry(), forEachKey(), forEachValue(), merge(), reduce() and search() methods.
  • CompletableFuture – that may be explicitly completed (setting its value and status).
  • Executors newWorkStealingPool() – method to create a work-stealing thread pool using all available processors as its target parallelism level.

3. New Date/ Time API

Current native Java library API is complex to implement and execute, so Joda time is a boon for Java developers in such situation. But, with coming of Java 8, the pain is cured as Java 8 came up with its own new Data/Time API under java.time package. New API is designed keeping simplicity in mind and it is easily readable to human and machine time formats. i.e. Simplified and Specialized date/ time API for local and zonal time zones respectively.

4. Stream API

A stream, a new abstract layer, provides a set of elements of a particular type in a consecutive manner. A stream executes element on demand, it never stores the elements. Alike SQL statements, data can be processed in a declarative way by using stream also. It is similar to an iterator which allows a single run over a collection. It is the best feature for developers who work on Collections and Big Data. Running of streams can be either sequential (stream () method) or parallel (parallelstream() method). Parallel enhances power of multiple cores.

5. Nashorn

Nashorn is a JavaScript engine which enables developer to run the script on a JVM. Compare to Rhino, its performance is 2 to 10 times better as it uses invoke dynamic feature. It is also suitable for Node.js applications along with supporting actual Java libraries to be called by the JavaScript code executing on a server. JAVA 8 introduces a new command line tool, jjs, to run JavaScript codes at console.

Quiet Java 8 Features

1. Parallel Sorting

Just as to speed up counting, Concurrent Accumulator is utilized, to speed up sorting, Parallel Sorting is adapted. It automatically splits the collection into several parts and sorts them independently based on cores and grouped them back. Arrays.parallelSort(myArray); is used for parallel sorting.

2. Commanding OS Processes

Java 8 came up with 3 new features in Process class which helps for controlling OS processes:

  • destroyForcibly – finishes a process with a higher degree of success
  • isAlive – indicates if a process originated by code is alive or not.
  • waitFor() – specifies the waiting time for a process to finish.

3. Stamped Locks

Java 8 advances ReadWriteLock (implemented by ReentrantReadWriteLock) with boosting speed called StampedLock. It has an “optimistic” mode that arises a stamp that is returned by each locking operation to assist as a kind of admission ticket; each unlock operation requires to pass its correlating stamp. The process results in faster execution. In situation where readers are more than writers, use StampedLock to improvise performance.

4. Secure Random Generation

Java 8 added up a new method called SecureRandom.getInstanceStrong() to enhance security. It let JVM choose a secure provider. For several years, security was one of the discussed issues of JVM, but with Java 8 feature it is reduces the risk of attack.

5. Null Reference Template

Null Pointers being an older pattern, Java 8 introduced a new template – Optional. Similar to the concept of Scala and Haskell, this template is to explicitly state when either reference is passed to or return by function can be null. This template increases convenience and decreases the time of execution.

Java 8 – A Platform for Business Innovation

Business apps develop using Java 8 development are faster and easily navigating with extended features. IoT (Internet of Things), an emerging technology nowadays, is also supported in Java 8. Apart from this, it also provides business leveraging peculiarities like more productivity, less time-consuming code, modernized apps, supporting embedded technology and much more. All above this, it is integrated with JavaScript. In short, Java 8 app development amplify the business app providing users a solution having robust functionalities.

Upcoming Java Updates

It is expected that Java 9 is launching this year (2017). It is tittle-tattle that Java 9 is coming up with features like Java 9 REPL (JShell), Factory Methods for Immutable List, Set, Map, and Map.Entry, Private methods in Interfaces, Module System, Process API Improvements, Resources Improvement, CompletableFuture API, Reactive Streams, Diamond Operator for Anonymous Inner Class, Optional Class advancement, Stream API fixes, Enhanced @Deprecated annotation, HTTP 2 Client, Мulti-Resolution Image API and few other miscellaneous features. Expected change in the ecosystem is of Modularity. Modules created, affects all phases of development – Compiling, testing, packaging, deploying, running. Due to this, Java 9 launch is stalled. It’s a thought that Java 9 is designed keeping in mind the developer’s request and issues.

The post Java 8 Features – Unleashed appeared first on TatvaSoft Blog.

]]>
https://www.tatvasoft.com/blog/java-8-features-unleashed/feed/ 0