Advantage of Hibernate over JDBC

1) Hibernate is data base independent, same code will work for all data bases like ORACLE,MySQL ,SQLServer etc.
In case of JDBC query must be data base specific.

2) As Hibernate is set of Objects , you don’t need to learn SQL language.
You can treat TABLE as a Object .
In case of JDBC you need to learn SQL.

3) Don’t need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance.
In case of JDBC you need to tune your queries.

4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance.
In case of JDBC you need to implement your java cache .
5) Hibernate supports Query cache and It will provide the statistics about your query and database status.
JDBC Not provides any statistics.

6) Development fast in case of Hibernate because you don’t need to write queries.

7) No need to create any connection pool in case of Hibernate. You can use c3p0.
In case of JDBC you need to write your own connection pool.

8) In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.

9) You can load your objects on start up using lazy=false in case of Hibernate.
JDBC Don’t have such support.

10 ) Hibernate Supports automatic versioning of rows but JDBC Not.


finalize(), finally and final in Java

There’s some confusion in the mind of an intermediate level programmer about finalize(),finally and final in java. So to remove that confusion from each and everyone’s mind I thought of writing a post on it.

finalize() : A Method
finally : A Clause in Try-Catch
final : Keyword in java

finalize :

It is called by the garbage collecter on an object by garbage collection when it knows that there is no references on the object. The finalize() method is defined in the java.lang.Object class and its modifier is defined as protected. The finalize() method is not public because it should only be invoked by JVM and not by anyone else and protected so that it can be overridden by the subclasses.

You can override the finalize() method and the declaration of the method should look like this :

protected void finalize() throws throwable


The below class opens the file when constructed :

class OpenAFile {
FileInputStream aFile = null;
OpenAFile(String filename) {
try {
aFile = new FileInputStream(filename);
} catch ( e) {
System.err.println(“Could not open file ” + filename);

As a part of good programming practice, the open file should be closed :

protected void finalize () throws throwable {
if (aFile != null) {
aFile = null;

It is important to understand that finalize() is only called just prior to garbage collection. It is not called when an object goes out-of-scope, for example. This means program should provide other means of releasing system resources, etc., used by the object. It must not rely on finalize() for normal program operation.

finally :

The finally clause defines a code that always executes, regardless of whether the exception was caught. The following sample code is taken from the book by Frank Yellin:

try {
} catch (Exception e) {
} finally {

In the above example the Faucet is turned off regardless of whether the exception was caught or not. The code inside the braces after try is called the protected code.

The only thing that stop finally from executing are virtual machine shutdowns i.e. System.exit method etc.

The final keyword in Java

Like other keywords in java, final is also a keyword used in several different contexts to define an entity which cannot later be changed.

Here in this tutorial we will be dealing with final classes, final methods, final variables and also I will be covering blank final variables.

    final classes

The Java Programming language permits us to apply the keyword final to classes. If the class is made final then it cannot be sub-classed.

Ex :

The java.lang.String is a final class. This is done for security reasons, because it ensures that if the method is referenced as String then the method is a definite string of class String and not a string of class which has sub-classed String class.

    final methods

Like class we can also mark methods as final. Methods that are marked as final cannot be overridden in any case. For security reasons only you must make the method as final if the method has implementation which you don’t want others to change.

Methods declared as final can be optimized. The compiler can generate a code that causes a direct call to the method, rather than invoking it the usual way i.e during the run-time.

    final variables

If a variable is marked as final then the value of that variable cannot be changed i.e final keyword when used with a variable makes it a constant. And if you try to change the value of that variable during the course of your program the compiler will give you an error.

NOTE: If you mark variable of a reference type as final, that variable cannot refer to any other object. However, you can change the object’s contents, because only the reference itself is final.

    Blank final variables

A blank final variable is a variable that is not initialized during its declaration. The initialization is delayed. A blank final instance variable must be assigned in a constructor, but it can be set only once. A blank final variable that is local variable can be set at any time in the body of the method, but it can be set only once.

The following code fragment is an example of how a blank final variable can be used in class.

public class Customer{
private final long customerID;

public Customer(){
customerID = createID();

public long getID(){
return customerID;

public long createID(){
return … // generates new ID
… // more declarations

Externalizable vs Seriablizable

Externalizable is an interface that enables you to define custom rules and your own mechanism for serialization. protocol and provides out of the box serialization capabilities.

Externalizable extends Seriablizable.

Implement writeExternal and readExternal methods of the Externalizable interface and create your own contract / protocol for serialization.

Saving the state of the super types is responsibility of the implementing class.

You might have seen in my previous article on how to customize the default implementation of Seriablizable. These two methods readExternal and writeExternal (Externalizable) supersedes this customized implementation of readObject and writeObject.

In object de-serialization (reconsturction) the public no-argument constructor is used to reconstruct the object. In case of Seriablizable, instead of using constructor, the object is re-constructed using data read from ObjectInputStream.

The above point subsequently mandates that the Externalizable object must have a public no-argument constructor. In the case of Seriablizable it is not mandatory.

Behaviour of writeReplace and readResolve methods are same for both Seriablizable and Externalizable objects. writeReplace allows to nominate a replacement object to be written to the stream. readResolve method allows to designate a replacement object for the object just read from the stream.

In most real time scenarios, you can use Seriablizable and write your own custom implementation for serialization by providing readObject and writeObject.

You may need Externalizable,

1. If you are not happy with the way java writes/reads objects from stream.

2. Special handling for super types on object construction during serialization.

Difference between inheritance and polymorphism?

This can be a confusing topic because one can argue that sharing method attributes between a super or abstract class with a derived class could be described by either Polymorphism or Inheritance. One significant difference could be illustrated as to when or under what circumstances you would you use one or the other.

An ideal instance of using Inheritance would be when you want to create an entirely new class, but wish to borrow a group of existing attributes or methods resident in an existing Abstract or super Class, instead of re-inventing the wheel. If you had an Abstract Class Carnivore and wanted to create a subclass Cat, you could instantly inherit all the methods that were common in Carnivore that applied to Cat without writing new code.

Polymorphism could be best applied when you had an existing SubClass that you wanted to modify or add a feature that could borrow a method that existed in a higher class. Take the Cat subclass, which inherited attributes from Carnivore, and you wanted to add the method Stalk, which would generically describe how a carnivore approaches its prey. However its implementation in Cat would detail the stealth it uses that are unique to a Cat.

Inheritance is the object oriented feature by which the functionality and features of one class are made available to another class without having to copy paste the code.

Polymorphism is the object oriented feature by which multiple methods of a class can coexist with minor differences. Ex: method overloading.

About serialVersionUID in Java Serialization

serialVersionUID is used to ensure that during deserialization the same class (tha was used during serialize process) is loaded. This is a one line definition to explain why a serialVersionUID is used?
Apart from the above definition there are quite a few things to learn from this serialVersionUID. As per javadocs, following is format of serialVersionUID:

serialVersionUID Syntax
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
serialVersionUID is a static final field. You can assign any number of your choice to it. Later I will explain the significance of these two statements.

Why serialVersionUID?
Let’s start with annoying warning message you get in your IDE when you declare a class as

The Seriablizable class Lion does not declare a static final serialVersionUID field of type long
Most of us used to ignore this message as we always do for a warning. My general note is, always pay attention to the java warning messages. It will help you to learn a lot of fundamentals.

serialVersionUID is a must in serialization process. But it is optional for the developer to add it in java source file. If you are not going to add it in java source file, serialization runtime will generate a serialVersionUID and associate it with the class. The serialized object will contain this serialVersionUID along with other data.
Even though serialVersionUID is a static field, it gets serialized along with the object. This is one exception to the general serialization rule that, “static fields are not serialized”.

How serialVersionUID is generated?
serialVersionUID is a 64-bit hash of the class name, interface class names, methods and fields.

Serialization runtime generates a serialVersionUID if you do not add one in source.

It is advised to have serialVersionUID as unique as possible. Thats why the java runtime chose to have such a complex algorithm to generate it.

If you want help in generating it, jdk tools provides a tool named serialver. Use serialver -show to start the gui version of the tool as shown below.

How serialVersionUID works?
When an object is serialized, the serialVersionUID is serialized along with the other contents.
Later when that is deserialized, the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class.

If the numbers do not match then,InvalidClassException is thrown.

If the loaded class is not having a serialVersionUID declared, then it is automatically generated using the same algorithm as before.

Strongly recommended to declare serialVersionUID
Javadocs says, “the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization”

Now you know why we should declare a serialVersionUID.

Not only declaring a serialVersionUID is sufficient. You must do the following two things carefully. Otherwise it defeats the purpose of having the serialVersionUID.

serialVersionUID should be maintained. As and when you change anything in the class, you should upgrade the serailVersionUID.

Try your best to declare a unique serialVersionUID.

Demonstrate serialVersionUID
Initial class to be serialized has a serialVersionUID as 1L.
public class Lion implements Serializable {
private static final long serialVersionUID = 1L;
private String sound;
public Lion(String sound) {
this.sound = sound;
public String getSound() {
return sound;

Test serialVersionUID:
public class SerialVersionUIDTest {
public static void main(String args[]) throwsIOException, ClassNotFoundException {
Lion leo = new Lion(“roar”);
// serialize
System.out.println(“Serialization done.”);
FileOutputStream fos = newFileOutputStream(“serial.out”);
ObjectOutputStream oos = newObjectOutputStream(fos);
// Deserialize
FileInputStream fis = newFileInputStream(“serial.out”);
ObjectInputStream ois = newObjectInputStream(fis);
Lion deserializedObj = (Lion) ois.readObject();
System.out.println(“DeSerialization done. Lion: ” + deserializedObj.getSound());

Serialization done.
Deserialization done. Lion: roar

Now change serialVersionUID to 2L in Lion class.

private static final long serialVersionUID = 2L;
Comment the “serialize” block (4 lines of code) in SerialVersionUIDTest. Now run it and you will get the following exception.

Serialized Lion with serialVersionUID with 1L.
Changed serialVersionUID to 2L and compiled and loaded the class
Deserialize the already serialized object and load it with the latest class
We get exception as serialVersionUID is not matching.

Exception in thread “main” Lion; local classincompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2
at Source)
at Source)
at Source)
at Source)
at Source)
at Source)
at SerialVersionUIDTest.main(

Difference between HTTP and HTTPS?

HTTP is hypertext transfer protocol which is responsible for transmitting and receiving information across the Internet whereas HTTPS is secure http, which is used exchanging confidential information with a server, which needs to be secured in order to prevent unauthorized access

HTTP transmits normal data whereas HTTPS transmits closed or encrypted data.

HTTP is for normal applications and HTTPS is mostly for banking or secure applications.

HTTP uses port 80 whereas HTTPS uses port 443

HTTP is defined in RFC 2616 and HTTPS is defined in RFC 2817

What is Association, Aggregation,Composition, Abstraction, Generalization

What is Association?

Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.

Example: A Student and a Faculty are having an association.

What is Aggregation?

Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. 

Aggregation is also called a “Has-a” relationship.

Aggregation is a relationship between two classes that is best described as a “has-a” and “whole/part” relationship. It is a more specialized version of the association relationship. 

The aggregate class contains a reference to another class and is said to have ownership of that class. Each class referenced is considered to be part-of the aggregate class.Ownership occurs because there can be no cyclic references in an aggregation relationship. 

If Class A contains a reference to Class B and Class B contains a reference to Class A then no clear ownership can be determined and the relationship is simply one of association.

For example, imagine a Student class that stores information about individual students at a school. Now let’s say there is a Subject class that holds the details about a particular subject (e.g., history, geography). If the Student class is defined to contain a Subject object then it can be said that the Student object has-a Subject object. The Subject object also makes up part-of the Student object, after all there is no student without a subject to study. The Student object is therefore the owner of the Subject object.


There is an aggregation relationship between Student class and the Subject class:

public class Subject {
private String name;
public void setName(String name)
{ = name;
public String getName()
return name;
public class Student {
private Subject[] studyAreas = new Subject[10];
//the rest of the Student class

What is Composition?

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

What is Abstraction?

Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.

Example: A wire frame model of a car.

What is Generalization?

Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behaviour are used from the specialization to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can relate this term very well. Generalization is also called a “Is-a” relationship.

Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.