Tuesday, 6 October 2015

How to avoid Subclass being serialization when super is serialized?

Avoid Subclass serialization when super is serialized:

To prevent subclass from being serialized we must implement writeObject() and readObject() method and need to throw NotSerializableException from these methods.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Human implements Serializable {
      private static final long serialVersionUID = 1L;

      String gender;

      Human(String gender) {
            this.gender = gender;
      }

      public String getGender() {
            return gender;
      }

      public void setGender(String gender) {
            this.gender = gender;
      }
}

class Man extends Human {

      private String name;

      Man(String gender, String name) {
            super(gender);
            this.name = name;
      }

      private void readObject(java.io.ObjectInputStream stream) {
            try {
                  throw new NotSerializableException();
            } catch (NotSerializableException e) {
            }
      }

      private void writeObject(java.io.ObjectOutputStream stream) {
            try {
                  throw new NotSerializableException();
            } catch (NotSerializableException e) {

            }
      }

      public String getName() {
            return name;
      }

      public void setName(String name) {
            this.name = name;
      }
}


public class Implementation {
      public static void main(String args[]) {

            /* Assigning values to Man class's instance.*/
            Man man = new Man("Male", "Andrew");

            /* Serializing Man's instance.*/
            try {
                  FileOutputStream fileOutputStream =
                             new FileOutputStream("serialObject.ser");
                  ObjectOutputStream objectOutputStream =
                             new ObjectOutputStream(fileOutputStream);
                  objectOutputStream.writeObject(man);

            } catch (FileNotFoundException e) {
                  e.printStackTrace();
            } catch (IOException ioe) {
                  ioe.printStackTrace();
            }

            /* Deserializing Man's instance. */
            Man manout = null;

            try {
                  FileInputStream fileInputStream =
                              new FileInputStream("serialobject.ser");
                  ObjectInputStream inputStream =
                              new ObjectInputStream(fileInputStream);
                  manout = (Man) inputStream.readObject();

            } catch (FileNotFoundException e) {
                  e.printStackTrace();
            } catch (IOException ioe) {
                  ioe.printStackTrace();
            } catch (ClassNotFoundException cnf) {
                  cnf.printStackTrace();
            }

            /*
             * Printing values from deserialized Man's object
             */
            System.out.println("Value of Deserailized instance :");
            System.out.println("Gender: " + manout.getGender());
            System.out.println("Name: " + manout.getName());
      }
}

Output:
Value of Deserailized instance :
Gender: Male
Name: null

Output: commenting the readObject and writeObject methods.
Value of Deserailized instance :
Gender: Male
Name: Andrew



Static block vs Static initialization

Static Block and Static variables initialized when the class loaded to JVM.
So, the order of execution is sequential.


public class StaticBlock {
      static {
            modifyIn = "static block 1";
            System.out.println("static block 1");
      }
     
      static {
            modifyIn = "static block 2";
            System.out.println("static block 2");
      }
     
      static String modifyIn = "static variable";

      public static void main(String args[]) {
            // modifyIn = String value modified by :static variable
            System.out.println("String value modified by :" + modifyIn);
      }
}

Output:
static block 1
static block 2
String value modified by :static variable



public class StaticBlock {
     
      static String modifyIn = "static variable";
     
      static {
            modifyIn = "static block 1";
            System.out.println("static block 1");
      }
     
      static {
            modifyIn = "static block 2";
            System.out.println("static block 2");
      }
     

      public static void main(String args[]) {
            // modifyIn = String value modified by :static block 2
            System.out.println("String value modified by :" + modifyIn);
      }
}
Output:
static block 1
static block 2
String value modified by :static block 2



Non-static initializer block

      {
            // Do something..
      }

This gets called every time the class is constructed. The static block only gets called once, no matter how many objects of that type you create.

On the other hand, static block called only once when the Object is loaded first time.



public class NonStaticBlock {
     
      static int a = 55;
     
      static {
            a = 6;
            System.out.println("static block called !!");
      }
     
      {
            a = 10;
            System.out.println("non-static block called !!");
      }
     
      public static void main(String args[]) {
            System.out.println(a);
           
            NonStaticBlock block = new NonStaticBlock();
            System.out.println(block.a);
           
            NonStaticBlock block1 = new NonStaticBlock();
      }
}
Output:
static block called !!
6
non-static block called !!
10
non-static block called !!

Monday, 5 October 2015

Prim's Algorithm

Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized.

For graphs that are sufficiently dense, Prim's algorithm can be made to run in linear time, meeting or improving the time bounds for other algorithms.

1.  Start at any node in the graph.
Mark the starting node as reached.
Mark all the other nodes in the graph as unreached.

#Minimum cost Spanning Tree (MST) consists of the starting node.

2. Find an edge e with minimum cost in the graph that connects a reached node x to an unreached node y.

3. Add the edge e found in the previous step to the MST.
Mark the unreached node y as reached.

4. Repeat the steps 2 and 3 until all nodes in the graph have become reached.


Pseudo code

ReachSet = {0};                    // You can use any node...
UnReachSet = {1, 2, ..., N-1};
SpanningTree = {};

while ( UnReachSet ≠ empty ) {
              Find edge e = (x, y) such that:
                    x ∈ ReachSet
                    y ∈ UnReachSet
                    e has smallest cost

              SpanningTree = SpanningTree ∪ {e};
              ReachSet   = ReachSet ∪ {y};
              UnReachSet = UnReachSet - {y};
}

Do you know it?


Developed by: Czech mathematician Vojtěch Jarník in 1930.

Rediscovered and republished by: computer scientists Robert C. Prim in 1957 and Edsger W. Dijkstra in 1959.

Why cannot Java constructors be synchronized?

According to the Java Language Specification, constructors cannot be marked synchronized because other threads cannot see the object being created until the thread creating it has finished it.

Syncronized on the constructor would prevent two threads from calling the constructor on the same Object simultaneously, and that is not possible, as it is never possible to call the constructor on an object instance twice, period.

And when the constructor is called you still don't have the object. It is logically impossible for two threads to access the constructor of the same object.

Collection hierarchy in Java


Interfaces



Low level hierarchy view





High level hierarchy view


Related Posts Plugin for WordPress, Blogger...