Friday 4 January 2019


  • A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be defined as,A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes.
  • In the above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01, 12, 23, 34, 04, 14, 13}.
  • Graphs are used to solve many real-life problems. Graphs are used to represent networks. The networks may include paths in a city or telephone network or circuit network. Graphs are also used in social networks like linkedIn, Facebook. For example, in Facebook, each person is represented with a vertex(or node). Each node is a structure and contains information like person id, name, gender, locale etc.



  • Serialization
    • Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object.
    • The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform.
    • To make a Java object serializable we implement the java.io.Serializable interface.
    • The ObjectOutputStream class contains writeObject() method for serializing an Object.
    • The ObjectInputStream class contains readObject() method for deserializing an object.
  • readResolve()
    • This ensures that nobody can create another instance by serializing and deserializing the singleton.
  • Advantages of Serialization
    • To travel an object across a network.
    • To save/persist state of an object.

  • Only the objects of those classes can be serialized which are implementing java.io.Serializable interface. Serializable is a marker interface (has no data member and method). It is used to “mark” java classes so that objects of these classes may get certain capability.
  • Other examples of marker interfaces are:- Cloneable and Remote.
  • Points to remember
    •  If a parent class has implemented Serializable interface then child class doesn’t need to implement it but vice-versa is not true.
    • Only non-static data members are saved via Serialization process.
    • Static data members and transient data members are not saved via Serialization process.So, if you don’t want to save value of a non-static data member then make it transient.
    •  Constructor of object is never called when an object is deserialized.
  • SerialVersionUID
    • The Serialization runtime associates a version number with each Serializable class called a SerialVersionUID, which is used during Deserialization to verify that sender and reciever of a serialized object have loaded classes for that object which are compatible with respect to serialization. 
    • If the reciever has loaded a class for the object that has different UID than that of corresponding sender’s class, the Deserialization will result in an InvalidClassException. A Serializable class can declare its own UID explicitly by declaring a field name.
  • Example
    • // Java program to illustrate loss of information // because of transient keyword. import java.io.*; class GfgAccount implements Serializable { String username = "gfg_admin"; transient String pwd = "geeks"; } class CustomizedSerializationDemo { public static void main(String[] args) throws Exception { GfgAccount gfg_g1 = new GfgAccount(); System.out.println("Username : " + gfg_g1.username + " Password : " + gfg_g1.pwd); FileOutputStream fos = new FileOutputStream("abc.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); // writeObject() method present in GfgAccount class // will be automatically called by jvm oos.writeObject(gfg_g1); FileInputStream fis = new FileInputStream("abc.ser"); ObjectInputStream ois = new ObjectInputStream(fis); // readObject() method present GfgAccount class // will be automatically called by jvm GfgAccount gfg_g2 = (GfgAccount)ois.readObject(); System.out.println("Username : " + gfg_g2.username + " Password : " + gfg_g2.pwd); } } ############### OUTPUT ############### Username : gfg_admin Password : geeks Username : gfg_admin Password : null
  • Customized Serialisation
    • During serialization, there may be data loss if we use the ‘transient’ keyword. ‘Transient’ keyword is used on the variables which we don’t want to serialize. But sometimes, it is needed to serialize them in a different manner than the default serialization (such as encrypting before serializing etc.), in that case, we have to use custom serialization and deserialization.
    • Customized serialization can be implemented using the following two methods:
      • private void writeObject(ObjectOutputStream oos) throws Exception: 
        • This method will be executed automatically by the jvm(also known as Callback Methods) at the time of serialization. Hence to perform any activity during serialization, it must be defined only in this method.
      • private void readObject(ObjectInputStream ois) throws Exception:
        •  This method will be executed automatically by the jvm(also known as Callback Methods) at the time of deserialization. Hence to perform any activity during deserialization, it must be defined only in this method.
    • Example
      • import java.io.*; class GfgAccount implements Serializable { String username = "gfg_admin"; transient String pwd = "geeks"; // Performing customized serialization using the below two methods: // this method is executed by jvm when writeObject() on // Account object reference in main method is // executed by jvm. private void writeObject(ObjectOutputStream oos) throws Exception { // to perform default serialization of Account object. oos.defaultWriteObject(); // epwd (encrypted password) String epwd = "123" + pwd; // writing encrypted password to the file oos.writeObject(epwd); } // this method is executed by jvm when readObject() on // Account object reference in main method is executed by jvm. private void readObject(ObjectInputStream ois) throws Exception { // performing default deserialization of Account object ois.defaultReadObject(); // deserializing the encrypted password from the file String epwd = (String)ois.readObject(); // decrypting it and saving it to the original password // string starting from 3rd index till the last index pwd = epwd.substring(3); } } class CustomizedSerializationDemo { public static void main(String[] args) throws Exception { GfgAccount gfg_g1 = new GfgAccount(); System.out.println("Username :" + gfg_g1.username + " Password :" + gfg_g1.pwd); FileOutputStream fos = new FileOutputStream("abc.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); // writeObject() method on Account class will // be automatically called by jvm oos.writeObject(gfg_g1); FileInputStream fis = new FileInputStream("abc.ser"); ObjectInputStream ois = new ObjectInputStream(fis); GfgAccount gfg_g2 = (GfgAccount)ois.readObject(); System.out.println("Username :" + gfg_g2.username + " Password :" + gfg_g2.pwd); } } ############### OUTPUT ############### Username :gfg_admin Password :geeks Username :gfg_admin Password :geeks

Saturday 29 December 2018


  • Inner class is a class defined inside other class and act like a member of the enclosing class.
  • There are two main types of inner classes
    • Static member class
    • Inner class
      • Member class
      • Anonymous class
      • Local class
  • Static member class
    • A static member class behaves much like an ordinary top-level class, except that it can access the static members of the outer
    • Outer class can access all inner class fields by referring Inner Class.(InnerA.printAnimal()). But inner class can access all static outer class properties and methods directly.
    • Both inner and outer classes can access others private properties and methods.
    • The static nested class can be accessed as the other static members of the enclosing class without having an instance of the outer class.
    •  The static class can contain non-static and static members and methods.
    • InnerClassTest1.java
      • public class InnerClassTest1 { private static int out = 1; public static class innerA { private static int number = 10; static void printAnimal(String animal) { System.out.println(out); System.out.println(animal); test(); } } private static void test() { System.out.println(innerA.number); } }
    • App.java
      • public class App { public static void main(String[] args) { InnerClassTest1.innerA.printAnimal("Tiger"); } }
  • Member class
    • Need to create Instance access properties and class out side the method.
    • Need Outer class object to create inner class object.
    • The member class can be declared as public, private, protected, final and abstract. E.g.
    • InnerClassTest2.java
      • public class InnerClassTest2 { private int out = 1; public class MemberClass { private void showName() { System.out.println("Sonu"); System.out.println(out); } } public void test() { MemberClass m = new MemberClass(); m.showName(); } }
    • App.java
      • public class App { public static void main(String[] args) { InnerClassTest2 o = new InnerClassTest2(); InnerClassTest2.MemberClass m = o.new MemberClass(); } }
  • Local class
    • It can be accessed only from same method.
    • Local classes cannot be public, private, protected, or static. (No access modifiers)
    • Local class can access all outer class properties and methods.
    • local class can access local variables and parameters of the enclosing method that are effectively final.
    • InnerClassTest3.java
      • public class InnerClassTest3 { int outerNumber = 1; public void methodTest() { int methodNumber = 2; class MethodLocalClass { private void showName() { System.out.println("SONU"); System.out.println(outerNumber); System.out.println(methodNumber); test(); } } methodNumber = 2; //error outerNumber =3; //will work MethodLocalClass m = new MethodLocalClass(); m.showName(); } public void test() { System.out.println("TEST"); } }
  • Anonymous class
    • These are local classes which are automatically declared and instantiated in the middle of an expression
    • Also, like local classes, anonymous classes cannot be public, private, protected, or static. 
    • They can define in the  arguments to the constructor of the outerclass, but cannot otherwise have a constructor.
    • They can implement only one interface or extend a class.
    • Anonymous class cannot define any static fields, methods, or classes, except for static final constants.
  • xxxx

Friday 21 December 2018


  1. ACID Properties in DBMS?
    1. A transaction is a single logical unit of work which accesses and possibly modifies the contents of a database. Transactions access data using read and write operations.In order to maintain consistency in a database, before and after transaction, certain properties are followed. These are called ACID properties.
    2. Atomicity
      1. By this, we mean that either the entire transaction takes place at once or doesn’t happen at all. There is no midway i.e. transactions do not occur partially. Each transaction is considered as one unit and either runs to completion or is not executed at all. 
    3. Consistency
      1. This means that integrity constraints must be maintained so that the database is consistent before and after the transaction. It refers to correctness of a database. 
    4. Isolation
      1. This property ensures that multiple transactions can occur concurrently without leading to inconsistency of database state. Transactions occur independently without interference. Changes occurring in a particular transaction will not be visible to any other transaction until that particular change in that transaction is written to memory or has been committed. This property ensures that the execution of transactions concurrently will result in a state that is equivalent to a state achieved these were executed serially in some order.
    5. Durability
      1. This property ensures that once the transaction has completed execution, the updates and modifications to the database are stored in and written to disk and they persist even is system failure occurs. These updates now become permanent and are stored in a non-volatile memory.
    6. The effects of the transaction, thus, are never lost.


    1. filter employees with same salary count greater than five (group by salary) using hibernate criteria?
      1. Session session = getCurrentSession(); ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.groupProperty("totalCode")) .add(Projections.groupProperty("activityCode")) .add(Projections.sum("amount")) .add(Projections.rowCount()); Criteria criteria = session.createCriteria(Payment.class); criteria.setProjection(projectionList); List payments = criteria.list(); for (Object[] payment : payments) { System.out.println("totalCode: " + payment[0]); System.out.println("activityCode: " + payment[1]); System.out.println("amountSum: " + payment[2]); System.out.println("rowCount: " + payment[3]); }
    2. What is Hibernate N+1 Problems and its Solution?
      1. Hibernate n+1 problems only comes for one to many relationship.
      2. Let us see this problem by example – We have Department table with a one-to-many relationship with Employee. One Department may have many Employees.
      3. We have written the Hibernate Department Entity as below.
      4. @Entity public class Department { private Long id; @OneToMany private Employee[] Employees; }
      5. So now you want to print out all the details of Employee models. A native O/R implementation would SELECT all Department and then do N additional SELECTs for getting the information of Employee for each department.
      6. -- To Get all Departments SELECT * FROM Department; -- To get each Employee, get Employee details SELECT * FROM Employee WHERE Employee.departmentId = ?
      7. As you see, the N+1 problem can happen if the first query populates the primary object and the second query populates all the child objects for each of the unique primary objects returned.
      8. Solution for Hibernate N+1 Problem
        1. Using HQL fetch join
          1. You can use the fetch while using the HQL as below example.
          1. from Department d join fetch d.employees Employee
          2. Hibernate Generated SQL would be similer as –
          3. SELECT * FROM Department d LEFT OUTER JOIN Employee e ON d.id = d.department_id
        1. Using Criteria query
          1. Criteria criteria = session.createCriteria(Department.class); criteria.setFetchMode("employees", FetchMode.EAGER);
        2. In both above cases, the query returns a list of Department objects with the Employee initialized, and only one query needs to be run to return all the Department and Employee information required.

Friday 7 December 2018

public class FirstWordUpperCase { public static void main(String[] args) { System.out.println(changeString("how are you man")); } private static String changeString(String str) { StringBuffer sb = new StringBuffer(); String[] arr = str.split("\\s"); for (int i = 0; i < arr.length; i++) { sb.append(Character.toUpperCase(arr[i].charAt(0))). append(arr[i].substring(1)).append(" "); } return sb.toString(); } }


  1. How to disable caching on back button of the browser?
    1. <% response.setHeader(“Cache-Control”,”no-store”); response.setHeader(“Pragma”,”no-cache”); response.setHeader (“Expires”, “0”); //prevents caching at the proxy server %>

Search This Blog

Contact us

Name

Email *

Message *