Tuesday 31 May 2016

How does ClassLoader Work?

When JVM requests for a class, it invokes ClassLoader.loadClass() method by passing the fully classified name of the Class.


public Class<?> loadClass(String name) throws ClassNotFoundException;


loadClass() method calls for findLoadedClass() method to check that the class has been already loaded or not. It’s required to avoid loading the class multiple times.


protected final Class<?> findLoadedClass(String name);


If the Class is not already loaded then it will delegate the request to parent ClassLoader to load the class.

If the parent ClassLoader is not finding the Class then it will invoke findClass() method to look for the classes in the file system.


protected Class<?> findClass(String name) throws ClassNotFoundException;

Java Classloader

The Java Classloader is a part of the JRE that dynamically loads Java classes into the JVM. Usually classes are only loaded on demand. The Java run time system does not need to know about files and file systems because of classloaders.





When the JVM is started, three class loaders are used:
Bootstrap class loader
Extensions class loader
System class loader

Bootstrap class loader
It loads the core Java libraries located in the <JAVA_HOME>/jre/lib directory. This class loader, which is part of the core JVM, is written in native code.

Extensions class loader
The extensions class loader loads the code in the extensions directories (<JAVA_HOME>/jre/lib/ext or any other directory specified by the java.ext.dirs system property). It is implemented by the sun.misc.Launcher$ExtClassLoader class.

System class loader
It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options. This is implemented by the sun.misc.Launcher$AppClassLoader class.


Monday 30 May 2016

Which constructor is called and why?


public class TestConstruct {

     public TestConstruct(Integer a) {
           System.out.println("It is an Integer");
     }

     public TestConstruct(long b) {
           System.out.println("It is a long");
     }

     public TestConstruct(int...x) {
           System.out.println("It is a int...");
     }

     public static void main(String[] args) {
           new TestConstruct(8);

     }
}

Output:
It is a long

Reason:
The general thumb rule is Widening (smaller primitive data type)> Autoboxing (wrapper) > Varargs.

public class TestConstruct {

            public TestConstruct(Integer a) {
                        System.out.println("It is an Integer");
            }

            public TestConstruct(long b) {
                        System.out.println("It is a long");
            }

            public TestConstruct(int... x) {
                        System.out.println("It is an int...");
            }

            public TestConstruct(int b) {
                        System.out.println("It is an int");
            }
           
            public static void main(String[] args) {
                        new TestConstruct(8);

            }
}
Output:
It is an int


Tuesday 24 May 2016

Depth-first search (DFS) in Java

Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.

The non-recursive implementation is similar to breadth-first search but differs from it in two ways: it uses a stack instead of a queue, and it delays checking whether a vertex has been discovered until the vertex is popped from the stack rather than making this check before pushing the vertex.

Input: A graph G and a vertex v of G
Output: All vertices reachable from v labeled as discovered

A recursive implementation of DFS: 
procedure DFS(G,v):
    label v as discovered
    for all edges from v to w in G.adjacentEdges(v) do
        if vertex w is not labeled as discovered then
            recursively call DFS(G,w)

A non-recursive implementation of DFS:       
procedure DFS-iterative(G,v):
    let S be a stack
    S.push(v)
    while S is not empty
          v = S.pop()
          if v is not labeled as discovered:
              label v as discovered
              for all edges from v to w in G.adjacentEdges(v) do
                  S.push(w)


Non recursive implementation of DFS:
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Stack;

public class GraphDFS {

   // No. of vertices
   private int vertives;
   //Adjacency Lists - Edges
   private LinkedList<Integer> adj[];

   GraphDFS(int vertices) {
      vertives = vertices;
      adj = new LinkedList[vertices];
      for (int i=0; i<vertices; ++i) {
         adj[i] = new LinkedList<Integer>();
      }
   }

   void addEdge(int v,int w) {
      adj[v].add(w);
   }

   private void traverseDFS(int node) {
      /** Mark true if vertices are visited. */
      boolean visited[] = new boolean[vertives];

      /** Create a queue for DFS */
      Stack<Integer> stack = new Stack<Integer>();

      /** mark start node as visited by default. */
      visited[node] = true;
      stack.add(node);

      while(!stack.isEmpty()) {

         /** poll the first element of queue. */
         node = stack.pop();

         System.out.print(node+" ");

         /** add all the nearest node of processing node. */
         Iterator<Integer> iter = adj[node].listIterator();
         while (iter.hasNext()) {
            int next = iter.next();
            if (!visited[next]) {
               visited[next] = true;
               stack.push(next);
            }
         }
      }
   }

   public static void main(String args[]) {

      /** Create a graph of size . */
      GraphDFS graph = new GraphDFS(4);

      /** Add edges in the graph.*/
      graph.addEdge(0, 1);
      graph.addEdge(0, 2);
      graph.addEdge(1, 2);
      graph.addEdge(2, 0);
      graph.addEdge(2, 3);
      graph.addEdge(3, 2);
      graph.addEdge(3, 1);

      System.out.println("DFS Traversal : ");

      /** start BS from any given node.*/
      graph.traverseDFS(1);
   }
}
Output:
DFS Traversal :
1 2 3 0

Breadth-first search (BFS) Implemetation in Java


import java.util.Iterator;
import java.util.LinkedList;

public class GraphBFS {

     // No. of vertices
     private int vertives;

     //Adjacency Lists - Edges
     private LinkedList<Integer> adj[];

     GraphBFS(int vertices) {
           vertives = vertices;
           adj = new LinkedList[vertices];
           for (int i=0; i<vertices; ++i) {
                adj[i] = new LinkedList<Integer>();
           }
     }

     void addEdge(int v,int w) {
           adj[v].add(w);
     }

     private void traverseBFS(int node) {
           /** Mark true if vertices are visited. */
           boolean visited[] = new boolean[vertives];

           /** Create a queue for BFS */
           LinkedList<Integer> queue = new LinkedList<Integer>();

           /** mark start node as visited by default. */
           visited[node] = true;
           queue.add(node);

           while(!queue.isEmpty()) {

                /** poll the first element of queue. */
                node = queue.poll();

                System.out.print(node+" ");

                /** add all the nearest node of processing node. */
                Iterator<Integer> iter = adj[node].listIterator();
                while (iter.hasNext()) {
                     int next = iter.next();
                     if (!visited[next]) {
                           visited[next] = true;
                           queue.add(next);
                     }
                }
           }
     }

     public static void main(String args[]) {

           /** Create a graph of size . */
           GraphBFS graph = new GraphBFS(4);

           /** Add edges in the graph.*/
           graph.addEdge(0, 1);
           graph.addEdge(0, 2);
           graph.addEdge(1, 2);
           graph.addEdge(2, 0);
           graph.addEdge(2, 3);
           graph.addEdge(3, 2);
           graph.addEdge(3, 1);

           System.out.println("BFS Traversal : ");

           /** start BS from any given node.*/
           graph.traverseBFS(1);
     }
}
Output
BFS Traversal:
1 2 0 3
Related Posts Plugin for WordPress, Blogger...