Notice

╠ This is my personal blog and my posts here have nothing to do with my employers or any other association I may have. It is my personal blog for my personal experience, ideas and notes. ╣

Sunday, August 9, 2020

New way to create immutable object in Java ['record'] JEP 384: Records

As a Java developer, we use POJO every day in our coding. We have to write or generate codes of accessor methods and other methods like 'equals', 'toString' and 'hashCode' or use a library like Lombok. 

To make it more simplified Java introducing 'record'. Using which developer need not have to generate or write these code. 

Some of the features of these 'record' class. 

  • implicitly they are final so it cannot be extended or abstracted but can implement an interface. 
  • java.lang.Record is the superclass of record 
  • A record cannot define the native method. 
  • A record field(s)  is/are implicitly final
Let's see with an example. 

A simple record with no boilerplate code. It provides field accessor method, 'toString', 'equals' and 'hashCode' readily available. 

A record with multiple constructors and instance method. 

A record with constructor level validation, static method and override 'equals' method. 

In this class, we are accessing the field with the internal method and other methods like 'toString', 'equals' and 'hashCode'. 


Output 

To compile these codes 

javac --enable-preview --release 15 TestRecord.java


To Run these codes 

java --enable-preview TestRecord



Happy coding and keep learning!

Sunday, July 26, 2020

Now Java Developer can write their 'Will' [JDK15 JEP 360: Sealed Class (Preview)]

As a developer if you want to control who can extend your class or interface. 

In this enhancement of Java programming language, new keywords are introduced sealed, non-sealed and permit at the class level. 

A sealed class or interface can be extended or implemented only by those classes and interfaces permitted to do so. If you try to implement or extend to other class which is not permitted then the code will not compile. For example,
public sealed class Point permits Line


permit keyword defines which are the subclasses or interfaces can be extended or implemented from this class. For example, 
public sealed class Point permits Line
Point class only permits Line class to extend directly. 

A non-sealed class or interface will allow this class to be extended. 
For example,
public non-sealed class Line
Permitted class Line is open for any unknown class extension. 



To Compile

To Run




A permitted subclass must define whether it could be extended to a specific class (sealed) or open to any unknown class(non-sealed) or not open for any extension (final). 



When a not permitted class extend a sealed class. 





Happy Coding and keep learning!

Saturday, July 18, 2020

JDK 15 [Pattern Matching of instanceof operator ]

This is an enhancement of Java language with pattern matching for the instanceof operator. Currently, this feature is in the second preview in JDK 15.

So currently when we need to cast an object, we check it using instanceof operation then only we cast the object to save our self from class cast exception.

existing instanceof operator

In the above code snippet, we have to explicitly cast it to an object. 
In this enhancement, we no more have to do it. 



To run the below code you need to install JDK 14 or above and have to enable the preview feature of javac & java. 
In order to enable that preview feature. 
javac 
      --enable-preview 
        -release <version> 
      <Source file>

java 
    --enable-preview 
       <Compiled class> 



Output

 Happy Coding!

Wednesday, May 20, 2020

Abstract Data Type

What is the data type?

A data type is an attribute in a programming language which define the domain of values and operations on that domain.

  • Define a certain domain of value. 
  • Define operations allowed on those values. 

Example 

int type
  • Take only integer values
  • Operations supported: addition, subtraction, multiplication, bitwise operation etc.  
float type 
  • Take only floating values 
  • Operations supported: addition, subtraction, multiplication, etc.  (it does not support operations like bitwise and modulus). 


Now, what is the user-defined data type? 

A user data type is NOT an attribute in a programming language but defines by the user which define the domain of values.

In below example, we define the user-defined data type using class. Here Person class is the type which is consist of bunch of String, LocalDate and Address fields. Person class have a user define a data type of Address.

Example

public class Person {
    private String firstName;
    private String lastName;
    private LocalDate dateOfBirth;
    private Address address;
   .....
}

public class Address {
   private String firstLine;
   private String lastLine,
   private State state;
  ....
}


Abstract Data Types (ADT)

Abstract Data Types (ADT) are like user define types which define values and operations on that user define type without specifying how the operation will happen.

Example

In this example, we will define an ADT where will create a data type named MyString class and define operations like addition, subtraction, multiplication and division. 

User Define Data Type 

  • MyString is a wrapper object of string. 
Let's define the operations of MyString data type.

User Define Operations 

  • The addition will concatenation two MyString. Example: "Hello" + " world" will result in "Hello world".
  • The subtraction will substring the difference of length. If the difference of length is zero or negative then it will have an empty string. Example: 
    • "Hello" - "world" will result in an empty string
    • "Hello" - "hi" will result in "Hel
    • "hi" - "Hello" will also result in an empty string. 
  • The division will remove common character(s) from MyString. Example: "Hello" / "world" will result in "He".
  • The multiplication will concatenate characters alternatively. Example: "Hello" * "world" will result in "Hweolrllod".

Actual Implementation 

Sample Unit Test of the Implementation 


Monday, April 27, 2020

One Time Password Generator

Simple code to generate One Time Password.
We are using java.util.SplittableRandom which was introduced in Java 8.

Output

Saturday, January 18, 2020

Exception flow control could be expensive.

As a developer sometimes we use exceptions as flow control. It could be expensive. I am going to show you how a simple change could help you to save a lot of time by simply not accepting exception as your code flow controller.
In this example, I will throw an exception if required data is not available during execution I will throw an IllegalArgumentException and in another case, I simply return a value using which call is going to take the decision based on the value then we will see how different it will be.




Code Output


In case of exception, it will take around a minute for execution and in another case it is insignificant. Both methods are invoked one million times to determine the impact.
Code Output
I request you to think again if you are using exception as your flow controller in a code which will be invoked many times.

Then what if I have to address an exception scenario 

If I need to address an exception scenario then for optimization I could pre-allocate the exception object so that I can use them multiple times.

Code Output


In this case, you can see the result is much better but still high than return statement.

Let me know your thoughts about it.