Tuesday, March 27, 2018

Java 10 JDK , Its Feature and How it is different From JDK 9


JDK 10 is officially released on 20th March 2018, as the short term release version , As you may know that , Java always release its new version on every 3 years  but after java 9 , it has decided to change the version way (i.e count like 7,8,9 ) rather will use the year of release as java 2018 like this , but they finally come over and released the short term release version of java as JDK 10 , the major release will be JDK 11.
Also read about : Java 9 and its features with examples

JDK 10 is now available on Oracle official site now , you can download it from
http://www.oracle.com/technetwork/java/javase/downloads/jdk10-downloads-4416644.html

Now as we talk about the features of JDK 10 

Features of JDK 10
There are some major changes we can see in JDK 10 :

1) Parallel Full GC for G1 : Full GC for G1 is released in Java 9 , Now Parallel Full GC support is provided , which will given to avoid the full collection (read more)

2) Local Variable Type Reference( support of var ) : This is one of the most awaiting feature for java to be added as most of the other programming language is already supporting the Local variable type reference feature but JAVA was the only popular programming language which was not supporting var support , but in JDK 10 , we can use var keyword
var str = "Java 10"; // infers String 
var list = new ArrayList<String>(); // infers ArrayList<String> 
var stream = list.stream(); // infers Stream<String>
3)Application class Data sharing : Now in Java 10 , we can share application classes as well , so what is class data sharing is , actually there is a shared class in JRE where JRE dump its file called shared archive, which is used to load the library of JRE. Now in Java 10 we can added the Application class as well in shared class.

4) Root Certificate :  Untill java 9 , there are 2 JDKs available OpenJDK and OracleJDK , Java need to maintain the build of both the jdk to be same so that they can used anywhere , Now in Java 10 , Root Certificate is included by help of which both the JDK will maintain the similarity.(read more)




5)Consolidated JDK Forest into Single Repository : Until java 9 , Java have 9 mini repository where it maintain its library online , these are  root, corba, hotspot, jaxp, jaxws, jdk, langtools, and nashorn. now from java 10 onward , they have consolidated all the mini repository into one single repository.

6)Heap Allocation on Alternate Memory Devices - This is one of the most important feature of java 10 as it shows the java vision of future , from java 10 onward , we can now able to use he memory devices to be used as allocation of heap memory . this will definitely going to change the perception of java for machines.

7)Shorter Start up time in JSHELL REPL.


8) API for Creating unmodifiable collection.

9) Support for multiples stylesheet in javadocs.

10) Thread-local handshake Improvement.

These are the Features of Java 10 , but remember java 10 is a short term release only .
The major release of java will be java 11


If you have any doubts on this please let me know , i will try my best to resolve .
Further read


Thank for reading
Noeik

Find Longest Common Ancestor(LCA) Program in java


Objective : The objective of this problem is to find the Longest Common Ancestor of the Tree.


Longest Common Ancestor is the common node in a tree who is common among the given 2 or more node.



Implementation :


import java.util.HashMap;
import java.util.Stack;

public class LCA {
    public static void main(String[] args) {
        // NOTE: The following input values will be used for testing your solution.
        // The mapping we're going to use for constructing a tree.
        // For example, {0: [1, 2]} means that 0's left child is 1, and its right
        // child is 2.
        HashMap<Integer, int[]> mapping1 = new HashMap<Integer, int[]>();
        int[] childrenA = {1, 2};
        int[] childrenB = {3, 4};
        int[] childrenC = {5, 6};
        mapping1.put(0, childrenA);
        mapping1.put(1, childrenB);
        mapping1.put(2, childrenC);

        TreeNode head1 = createTree(mapping1, 0);

        // This tree is:
        // head1 = 0
        //        / \
        //       1   2
        //      /\   /\
        //     3  4 5  6


        HashMap<Integer, int[]> mapping2 = new HashMap<Integer, int[]>();
        int[] childrenD = {1, 4};
        int[] childrenE = {3, 8};
        int[] childrenF = {9, 2};
        int[] childrenG = {6, 7};
        mapping2.put(5, childrenD);
        mapping2.put(1, childrenE);
        mapping2.put(4, childrenF);
        mapping2.put(3, childrenG);

        TreeNode head2 = createTree(mapping1, 5);
        // This tree is:
        //  head2 = 5
        //        /   \
        //       1     4
        //      /\    / \
        //     3  8  9  2
        //    /\
        //   6  7


        // lca(head1, 1, 5) should return 0
        // lca(head1, 3, 1) should return 1
        // lca(head1, 1, 4) should return 1
        // lca(head1, 0, 5) should return 0
        // lca(head2, 4, 7) should return 5
        // lca(head2, 3, 3) should return 3
        // lca(head2, 8, 7) should return 1
        // lca(head2, 3, 0) should return null (0 does not exist in the tree)
    }


    // Implement your function below.
    public static TreeNode lca(TreeNode root, int j, int k) {
        Stack<TreeNode> pathToJ = pathToX(root, j);
        Stack<TreeNode> pathToK = pathToX(root, k);
        if (pathToJ == null || pathToK == null) {
            return null;
        }

        TreeNode lcaToReturn = null;

        while (!pathToJ.isEmpty() && !pathToK.isEmpty()) {
            TreeNode jPop = pathToJ.pop();
            TreeNode kPop = pathToK.pop();
            if (jPop == kPop) {
                lcaToReturn = jPop;
            } else {
                break;
            }
        }
        return lcaToReturn;
    }

    public static Stack<TreeNode> pathToX(TreeNode root, int x) {
        if (root == null) {
            return null;
        }

        if (root.value == x) {
            Stack<TreeNode> path = new Stack<TreeNode>();
            path.push(root);
            return path;
        }

        Stack<TreeNode> leftPath = pathToX(root.left, x);
        if (leftPath != null) {
            leftPath.push(root);
            return leftPath;
        }

        Stack<TreeNode> rightPath = pathToX(root.right, x);
        if (rightPath != null) {
            rightPath.push(root);
            return rightPath;
        }

        return null;
    }

    // A function for creating a tree.
    // Input:
    // - mapping: a node-to-node mapping that shows how the tree should be constructed
    // - headValue: the value that will be used for the head ndoe
    // Output:
    // - The head node of the resulting tree
    public static TreeNode createTree(HashMap<Integer, int[]> mapping, int headValue) {
        TreeNode head = new TreeNode(headValue, null, null);
        HashMap<Integer, TreeNode> nodes = new HashMap<Integer, TreeNode>();
        nodes.put(headValue, head);
        for(Integer key : mapping.keySet()) {
            int[] value = mapping.get(key);
            TreeNode leftChild = new TreeNode(value[0], null, null);
            TreeNode rightChild = new TreeNode(value[1], null, null);
            nodes.put(value[0], leftChild);
            nodes.put(value[1], rightChild);
        }
        for(Integer key : mapping.keySet()) {
            int[] value = mapping.get(key);
            nodes.get(key).left = nodes.get(value[0]);
            nodes.get(key).right = nodes.get(value[1]);
        }
        return head;
    }
 }

In this Implementation we have used the Stack and hashmap , Also if you see the Comments all the functionality should be clear .


If you have any issue or you are not able to undertand the program, leave us a comment.

Thanks for reading
Noeik

Sunday, March 25, 2018

Wrapper Classes in java


Wrapper Classes - Have you ever heard about them , if not , no issue you will get to know about it in this post.
There are some other post related to this , which can be helpful are
  1. Making Games With Java- Introduction
  2. Getting Everything you need for Java
  3. Introduction to Java Programming
  4. Basic data types and Variables in java
  5. Basic Data types and Variables in java - Continued...
  6. User Input using Scanner class in java
  7. Conditional Logic in java
  8. Loops in java
  9. Arrays in java


Wrapper Classes – why are they needed?

There is a class that has been dedicated to each of the 8 primitive data types in java. These primitive types are int, float, char, byte, long, short, boolean and double. The dedicated classes that “wrap” over these primitive types are called Wrapper Classes.
int num = 10; // primitive type
Integer num = new Integer(10); // wrapper class
The main purpose of these wrapper classes is:
  • To enable primitives to perform activities that can be performed by objects. For example being added to a collection
  • To be able to perform the different utility functions like converting to and from String objects, comparison on primitives

How can we create Wrapper Classes?

There are 2 ways of creating wrapper class instances in Java.

Using Constructor:

Constructors of the corresponding wrapper classes can be used to create instances with the help of the new keyword.
1)Accepts the primitive type as parameter
          Example: Integer num = new Integer (10);
2)Accepts string as parameter (except Character)
          Example: Integer num = new Integer ("10");

Using the valueOf method:

Another way of creating Wrapper class objects is by using the valueOf method.
There are 3 variants of this method.

1)Accepts primitive type as parameter
This statement will return an Integer object containing the value represented by the primitive type.
2)Accepts String parameter
This returns the Integer object for the String passed as parameter.
3)Accepts two parameters a String and radix.
The radix parameter will be used to determine the value of the Integer that is returned based on the String parameter passed.

The following example shows how both these ways can be used to create wrapper class instances:
public class WrapperExample {
    public static void main(String args[]) {
      Integer numint1 = new Integer (10);
      //or
      Integer numint2 = 10;
      Integer numStr = new Integer ("20");
   
      
      Integer withValueOf1 =Integer.valueOf(9);
      Integer withValueOf2 =Integer.valueOf("9");             
      Integer withValueOf3 = Integer.valueOf("444",16);

      System.out.println("numint1 = "+numint1); 
      System.out.println("numint2 = "+numint2);
      System.out.println("numStr = "+numStr);
      
      
      System.out.println("withValueOf1 = "+withValueOf1);
      System.out.println("withValueOf2 = "+withValueOf2);
      System.out.println("withValueOf3 = "+withValueOf3);
    }
}
In the above example, we can see the ways of creating wrapper class instances in java. When creating using constructors, one needs to be aware of the wrapper class name and the parameters it accepts.
As the wrapper classes come in last in the hierarchy, there is no subclass that one can get from them.


The constructor that accepts String parameters may throw NumberFormatexception if the string passed cannot be parsed into an Integer.

Using the valueOf() method seems more efficient as it returns cached objects which means that it is not always necessary to create a new object.

Autoboxing  and its advantages

  • When a primitive type is automatically converted to its corresponding wrapper object it is called autoboxing
  • This reduces code to convert from primitive types to Wrapper equivalents thus leading to cleaner code.
The following statement from the code above is the perfect example of autoboxing.
Integer numint2 = 10;
The above statement is an example of auto boxing.

Auto-boxing is done in the following cases:
  • When a primitive is passed as a parameter where an object of the corresponding wrapper class is expected.
  • When a primitive is assigned to a variable of the corresponding wrapper class as seen in the example above.
Following code snippet demonstrates auto-boxing for character:
//auto boxing
Character chWrapper = 'a';
// Auto-unboxing 
char ch = chWrapper;

Casting in Java – Implicit and explicit Casting

Taking an object of one type and converting it into another is the simplest way in which we can define Casting.
But obviously there are some rules that need to be followed. You cannot just take one variable and convert it into another type.

Implicit Casting:

  • Automatic type conversion or implicit casting happens if both the concerned types are compatible with each other and the target is larger/wider than the source.
  • No casting is specifically required in the case of implicit casting.
Examples:
short sh = 10;
 int num = sh;
 long l = num;
float fl = l;
double d = fl;
public class CastingExample {
    public static void main(String args[]) {
        short sh = 10;
        int num = sh;
        long l = num;
        float fl = l;
        double d = fl;

        System.out.println("Value of sh: " + sh);
        System.out.println("Value of num: " + num);
        System.out.println("Value of l: " + l);
        System.out.println("Value of fl: " + fl);
        System.out.println("Value of d: " + d);
    }
}
The implicit casting can be done in the following order only.
In inheritance too, implicit casting is present when we assign a child object to a parent class instance.
Example:
class Parent
{
 public void method()
 {
 // method body
 }
}
public class Child extends Parent
{
 public static void main(String args[])
 {
  Parent p = new Child();
  p.method();
 }
}

Explicit Casting:

If both the concerned types are compatible with each other but the source is larger/wider than the target then it is called explicit casting.
Here the conversion will happen the other way around.
To achieve narrowing, explicit casting needs to be done
double d = 75.0;
// Explicit casting 
float fl = (float) d;
long l = (long) fl;
int num  = (int) l;
short sh = (short) num;
public class CastingExample {
    public static void main(String args[]) {
        double d = 75.0;
// Explicit casting 
float fl = (float) d;
long l = (long) fl;
int num  = (int) l;
short sh = (short) num;
        System.out.println("Value of sh: " + sh);
        System.out.println("Value of num: " + num);
        System.out.println("Value of l: " + l);
        System.out.println("Value of fl: " + fl);
        System.out.println("Value of d: " + d);
    }
}
Similarly, in inheritance we can explicitly cast super type to a sub type.
Example
class Parent
{
 public void disp()
 {
  // method body
 }
}
public class Child extends Parent
{
 public void disp()
 {
  // method body
 }
 public static void main(String args[])
 {
  Parent p = new Child();
  p.disp();
  Child c = (Child)p;
  c.disp();
 }
}
Explicit casting to child class needs to be done to achieve this as seen in the code, Child c = (Child)p;


To summarise:
  • To be able to use the specific functionality of the target type, casting is done. When converting float to long I am able to store more data in it.
  • In the same way if we want to access some methods from a super class using the subclass variables we can use casting.
  • The object itself is not changed when you perform casting.
  • There has to be compatibility between the source and target types when casting. I cannot cast a variable of a subclass of A to a parent of B.
  • Upcasting or Implicit Casting can be automatic as it will never fail.
  • Downcasting or Explicit casting on the other hand may throw a ClassCastException in some cases. This is where the instanceof check can come in handy.
If you liked this post , please share it with your friends and colleagues. 

Thanks for reading 

Wednesday, March 21, 2018

Arrays in java

Another pretty important component in Java programming is the use of Arrays. Like variables and loops, most of the program you will write will make use of them.
An Array can be defined as an data type that holds a collection of of a similar data type. with having consecutive memory allocation.




Before more further let see previous post of series
  1. Making Games With Java- Introduction
  2. Getting Everything you need for Java
  3. Introduction to Java Programming
  4. Basic data types and Variables in java
  5. Basic Data types and Variables in java - Continued...
  6. User Input using Scanner class in java
  7. Conditional Logic in java
  8. Loops in java

What are arrays used for?

There are two main uses of arrays:
  •     Conecutive Memory Allocation
  •     Easy Data access ( as index fetch )
Now consider this: you have to create the programme that finds the average age of thirty people. You can do this in two ways. You could:
  1. Create 30 separate age variables (age1, age2… age30) and define values for each of them one by one, before actually calculating the average. This is very inefficient, tedious, and will make the code unnecessarily lengthy.
  2. Or you could store all thirty age values into a single Integer array, which you could call something like ‘Age’. Not only will this be less stressful, it also makes it easier to access data through the array index.
Arrays in Java are index-based i.e. elements stored in array are accessed through their index values. And array indices also start from 0. Therefore, the first element is stored at 0, the second at 1, etc.
Is there a con to arrays?
  • The major disadvantage to arrays is that they can only contain a fixed number of elements, which cannot be changed at runtime.
  • You need to declare the size of the array at the compile time only.
Declaring Arrays.
Array and variable declaration have the same basic principle. You state the data type you want to use with the array (int, char, float, etc.), you give the array a name and save the value into it. The main difference is the addition of square brackets ([]), which is basically the universal coding symbol for arrays.
Below, I have created an integer array variable named arrayInt:
int arrayInt [] ;
You can see that it looks like a basic integer variable, with the addition of the square brackets to the end of variable name.
Note, the square bracket can be added to the back of the data type instead of the variable name, like so this is also valid declaration.
int [] arrayInt ;

Also take note that in the naming of arrays, the rules that apply to naming of variables apply. If you’re not sure what they are, please click this link. You can also turn any data type into an array. You can create a String array:
String arrayString [];
… a Float array:
float arrayFloat [];
… and even a Boolean array:
boolean arrayBool [];
But we don’t know how many values can be saved into the arrays yet. To set this, in the integer array for example, go to the next line and type this in:
arrayInt = new int [5];
According to the code above, this array has a limit of five values. It will not accept or recognise any more values after the fifth.
You can also declare the array limit on the same line where you declared the array:
int[] arrayInt = new int[5];
So now we’ve created an integer array called ‘arrayInt’, that can hold up to five integer values.  Now that we’ve set the array, the system will assign default values of zero to all array positions.
Now, assign values 1 to 5 in each array position:
arrayInt [0] = 1;
arrayInt [1] = 2;
arrayInt[2] = 3;
arrayInt[3] = 4
arrayInt[4] = 5;    
System.out.println(arrayInt[2]); 
Now, we’ve assigned values to each and every memory space in the array, and we’ve set a print statement to print out the third value (the value with the memory space [2]. The code in your coding window should look a lot like this:
Now run your programme, it means your output was this:
But if you’re like me, and would rather do everything one line, you could just as well do this:
int [] arrayInt = {1, 2, 3, 4, 5};
Note, you don’t have to specify the number in the square bracket. The number of values you set will automatically be the set as the array limit.
You probably also noticed that you no longer needed to use the new keyword, or repeat the data type, or put another square bracket. Let me warn that this will only work in the case of int, String and char values. You can do this:
char [] arrayChar = {'A', 'B', 'C', 'D'};
…or this:
String [] arrayString = {"My", "name", "is", "Vishal"};
But not this:
boolean [] arrayBool = {true, false, false, true};
For that, you’d have to do this:
Boolean [] arrayBool = new Boolean [] {true, false, false, true};

Arrays and Loops

If there’s anything that arrays work well with, it’s loops. In fact, any program that uses arrays would most likely make use of loops, and loops can also be used interchangeably with arrays.
Let’s take the integer array we made earlier and join it with a loop. Remove the print statement and replace it with this for loop:
for(int i = 0; i < arrayInt.length; i++){
    System.out.println(arrayInt[i]);
}
Run it and it will count every number in the integer array, from 1 to 5, like this:
Another thing you can do with loops and array is use a loop to set values to your array. I mean, in the beginning, I said that we could assign values to the array by doing this:
arrayInt[2] = 3;
But this would be tedious for assigning values to, let’s say, thirty values or more. Like now, instead of just typing a long list of variables and values repetitively, we could just as easily use a loop. Comment out everything you’ve done so far and type this down:
int[] arrayInt = new int[30];
for(int i = 0; i < arrayInt.length; i++){
arrayInt[i] = i + 1;
System.out.println(arrayInt[i]);
}
Then run it, and your result should be this:
I enlarged my output table to show all the values. You can do this by holding your cursor over the output window until you see the arrow pointing up and down, then drag up.
Multi-Dimensional Arrays
So far, the arrays we’ve been looking at are one-dimensional (they can only take one column of data). But you can set up arrays that hold data in rows and columns; kind of like a matrix.
These arrays are called Multi-Dimensional Arrays. They are declared the same way as one-dimensional arrays, except they have two square brackets instead of one:
int [] [] arrayInt = new int [4] [4];
The first square bracket shows the number of rows in the array while the second shows the number of columns. 
The above array has four rows and four columns.

Assigning values to Multi-Dimensional Arrays
To assign values to a multi-dimensional array, you must specify the row and column numbers you want the value to be saved in. For instance:
arrayInt [0][0] = 1;
arrayInt[0][1] = 2;
arrayInt[0][2] = 3;
arrayInt[0][3] = 4;
The first row is 0, so every value is assigned to that row. 
The columns count from 0 to 3, which is four values. To fill the second row, you would have to change the value in the first brackets from 0 to 1, leaving the column values the same.
Continue adding values until you’ve filled every row and column. When you’re done, you should have something like this:
Now normally, before we printed out every value in an array, we would use a for loop. That is the same case in multi-dimensional array, except in this case, you’ll need two for loops. One for the rows, and the other for columns.
Quickly add these lines to your code:
So, the two loops are set to run until their values reach the limits of our rows and columns, printing out our values as thus:

Now if we see the full Program of array 


package tutorialproject;


public class Arrays {

   
    public static void main(String[] args) {
        int[][] arrayInt = new int [4][4];
        
            arrayInt[0][0] = 1;
            arrayInt[0][1] = 2;
            arrayInt[0][2] = 3;
            arrayInt[0][3] = 4;

            arrayInt[1][0] = 5;
            arrayInt[1][1] = 6;
            arrayInt[1][2] = 7;
            arrayInt[1][3] = 8;
            
            arrayInt[2][0] = 9;
            arrayInt[2][1] = 10;
            arrayInt[2][2] = 11;
            arrayInt[2][3] = 12;
            
            arrayInt[3][0] = 13;
            arrayInt[3][1] = 14;
            arrayInt[3][2] = 15;
            arrayInt[3][3] = 16;
            
            int rows = 4;
            int columns = 4;
            int i, j;
            
            for(i = 0; i < rows; i++){
                for(j = 0; j < columns; j++){
                    System.out.print(arrayInt[i][j] + " ");
                }
            }
            
            System.out.println();
        }
        
    }

I hope you have learned something in this post , if you liked it please share it with your friends and colleagues ,

Happy learning
Noeik