What is use of serialVersionUID


 During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type
Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass’s computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.

Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:

  • Add fields
  • Change a field from static to non-static
  • Change a field from transient to non-transient
  • Add classes to the object tree

List of incompatible changes:

  • Delete fields
  • Change class hierarchy
  • Change non-static to static
  • Change non-transient to transient
  • Change type of a primitive field

So, if no suid is present , inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used .
The only way to get rid of the exception is to recompile and deploy the application again.

If we explicitly metion the suid using the statement:

private final static long serialVersionUID = <integer value>

then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.

Dependency Injection in Spring


Dependency Injection (DI): is a way to let the framework or the container work out the complexities of service instantiation, initialization and sequencing and supplies the service references to the clients as required. In spring IOC container has the responsibility of doing DI.

 

Consider a simple example:

 

public interface Vehicle {

                 void displayData();

}

 

A FourWheeler class implements Vehicle interface.

 

public class FourWheeler implements Vehicle {

 

      private String name;

      private int purchaseValue;

      private int noOfTyres;

      public FourWheeler(){}                          // default constructor                   

public FourWheeler(String name, int purchaseValue, int noOfTyres) {

            super();

            this.name = name;

            this.purchaseValue = purchaseValue;

            this.noOfTyres = noOfTyres;

      }

      public void displayData() {

            System.out.println(” Name of vehicle is “+ name);

            System.out.println(“Purchase Value is “ +purchaseValue);

            System.out.println(“Tyres the vehicle has “ +noOfTyres);

      }

      public String getName() {

            return name;

      }

      public void setName(String name) {

            this.name = name;

      }

      public int getPurchaseValue() {

            return purchaseValue;

      }

      public void setPurchaseValue(int purchaseValue) {

            this.purchaseValue = purchaseValue;

      }

      public int getNoOfTyres() {

            return noOfTyres;

      }

      public void setNoOfTyres(int noOfTyres) {

            this.noOfTyres = noOfTyres;

      }

}

 

The different ways in which the class can be instantiated using DI in spring.xml:

 

1) Setter based injection: The values of the properties of the class are set with the help of setter. Each class needs to declare the setter of the properties and their values are set from the spring configuration file.

 

 <?xml version=“1.0” encoding=“UTF-8”?>

<!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN//EN” http://www.springframework.org/dtd/spring-beans.dtd&#8221;>

<beans>      

       <bean id=“fourWheeler” class=“com.src.FourWheeler”> 

            <property name=“noOfTyres”> <value>4</value>

            </property>

           

<property name=“name” value=“Honda”/>                                  

<property name=“purchaseValue” value=“900000”/>  

      </bean>

</beans>

 

In above example the setter methods are created for noOfTyres, name, purchaseValue in FourWheeler  class and the values are set using <property> <value> tag in xml file.

Note that for each property the value is set using a different syntax. All syntaxes are valid and

can be used depending on the programmer liking. In this declaration the default constructor of class is called.

 

2)  Constructor Based injection: In this case the values are set using constructor of the java class. The call to constructor is made from the xml file using <constructor-arg>.  For the above mentioned java class constructor injection will be:

 

<?xml version=“1.0” encoding=“UTF-8”?>

<!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN//EN” http://www.springframework.org/dtd/spring-beans.dtd&#8221;>

<beans >      

     

      <bean id=“fourWheeler” class=“com.src.FourWheeler”> 

                        <constructor-arg> index=“0” value=“Honda”/>

                        <constructor-arg type=“Integer”>

                              <value>900000</value>

                  </constructor-arg>

      </bean>    

</beans>

 

 

In the above example the values to the bean is passed using <constructor-arg>. The sequence in which the parameters are passed should match with the constructor available in the class.

 

3) Static factory method: In the less common case where the container invokes a static, factory method on a class to create the bean, the class property specifies the actual class containing the static factory method that is to be invoked to create the object (the type of the object returned from the invocation of the static factory method may be the same class or another class entirely.

 

Consider the following method present in FourWheeler class:

public static TwoWheeler createInstance(){

            return new TwoWheeler();

      }

 

Note that the method has to be static. And following line of code in xml:

 

<bean id=“twoWheeler” class=“com.src.FourWheeler” factory-method=“createInstance”/>

 

After execution of the above line twoWheleler bean will represent the TwoWheeler object which is created by calling the function from FourWheeler Class. The attribute factory-method tells which method to call present in the class mentioned. This scenario could possibly use in cases where Factory pattern is required.

 

4) Instance Factory method: In this case instead of having a static method a non-static method is present to create the object.

 

Consider the following method present in FourWheeler class:

public TwoWheeler createInstance(){

            return new TwoWheeler();

      }

 

Note that the method need not be static. And following line of code in xml:

 

<bean id=“parentfourWheeler” class=“com.src.FourWheeler”/>

 

<bean id=“fourWheeler” factory-bean = “parentFourWheeler” factory-method=“createInstance” />

 

Here the twoWheeler object is created from a non-static method of class FourWheeler.

Use of hashcode() and equals()


Use of hashCode() and equals(). 

Object class provides two methods hashcode() and equals() to represent the identity of an object. It is a common convention that if one method is overridden then other should also be implemented.

Before explaining why, let see what the contract these two methods hold. As per the Java API documentation:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashcode() method must consistently return the same integer, provided no information used in equals() comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.
  • It is NOT required that if two objects are unequal according to the equals(Java.lang.Object) method, then calling the hashCode() method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Now, consider an example where the key used to store the in Hashmap is an Integer. Consider that Integer class doesn’t implement hashcode() method. Just for this example The code would look like:

  map.put(new Integer(5),”Value1″);
String value = (String) map.get(new Integer(5));
System.out.println(value);
//Output : Value is null

Null value will be displayed since the hashcode() method returns a different hash value for the Integer object created at line 2and JVM tries to search for the object at different location.

Now if the integer class has hashcode() method like:

public int hashCode(){
return value;
}

Everytime the new Integer object is created with same integer value passed; the Integer object will return the same hash value. Once the same hash value is returned, JVM will go to the same memory address every time and if in case there are more than one objects present for the same hash value it will use equals() method to identify the correct object.

Another step of caution that needs to be taken is that while implementing the hashcode() method the fields that are present in the hashcode() should not be the one which could change the state of object.

Consider the example:

publicclass FourWheeler implements Vehicle {

 

      private String name;

      privateintpurchaseValue;

      privateintnoOfTyres;

      public FourWheeler(){}

 

public FourWheeler(String name, int purchaseValue) {

            this.name = name;

            this.purchaseValue = purchaseValue;

      }

      publicvoid setPurchaseValue(int purchaseValue) {

            this.purchaseValue = purchaseValue;

      }

 

      @Override

      publicint hashCode() {

            finalint prime = 31;

            int result = 1;

            result = prime * result + ((name == null) ? 0 : name.hashCode());

            result = prime * result + purchaseValue;

            return result;

      }

}

FourWheeler fourWObj = new FourWheeler(“Santro”,”333333);
map.put(fourWObj,”Hyundai);
fourWObj.setPurchaseValue(“555555)
System.out.println(map.get(fourWObj));
//Output: null

We can see that inspite of passing the same object the value returned is null. This is because the hashcode() returned on evaluation will be different since the purchaseValue is set to ‘555555’ from ‘333333’. Hence we can conclude that the hashcode() should contain fields that doesn’t change the state of object.

One compatible, but not all that useful, way to define hashCode() is like this:

public int hashcode(){
return 0;
}

This approach will yield bad performance for the HashMap. The conclusion which can be made is that the hashcode() should(not must) return the same value if the objects are equal. If the objects are not equal then it must return different value.

Overriding equals() method

Consider the example:

publicclass StringHelper {

 

      private String inputString;

     

      public StringHelper(String string) {

            inputString=string;

      }

 

      @Override

      publicint hashCode() {

            returninputString.length();

      }

   

 

      publicstaticvoid main(String[] args) {

           

            StringHelper helperObj = new StringHelper(“string”);

            StringHelper helperObj1 = new StringHelper(“string”);

            if(helperObj.hashCode() == helperObj1.hashCode()){

                  System.out.println(“HashCode are equal”);

            }

            if(helperObj.equals(helperObj1)){

                  System.out.println(“Objects are equal”);

            }else{

                  System.out.println(“Objects are not equal”);

            }

 

      }

 

      public String getInputString() {

            returninputString;

      }

 

// Output:
HashCode are equal
Objects are not equal

We can see that even though the StringHelper object contains the same value the equals method has returned false but the hashcode method has return true value.

To prevent this inconsistency, we should make sure that we override both methods such that the contract between both methods doesn’t fail.

Steps that need to be taken into consideration while implementing equals method.

1. Use the == operator to check if the argument is a reference to this object.                                                                If so, return true. This is just a performance optimization, but one that is worth doing if the comparison is potentially expensive.

2. Use the instanceof operator to check if the argument has the correct type.

If not, return false. Typically, the correct type is the class in which the method occurs. Occasionally, it is some interface implemented by this class. Use an interface if the class implements an interface that refines the equals contract to permit comparisons across classes that implement the interface. Collection interfaces such as Set, List, Map, and Map.Entry have this property.

3. Cast the argument to the correct type. Because this cast was preceded by an instanceof test, it is guaranteed to succeed.

4. For each “significant” field in the class, checks if that field of the argument matches the corresponding field of this object.          If all these tests succeed, return true; otherwise, return false

5. When you are finished writing your equals method, ask yourself three questions: Is it symmetric? Is it transitive? Is it consistent?

The correct implementation if equals method for the StringHelper class could be:

@Override

      publicboolean equals(Object obj) {

            if (this == obj)

                  returntrue;

            if (obj == null)

                  returnfalse;

            if (getClass() != obj.getClass())

                  returnfalse;

            final StringHelper other = (StringHelper) obj;

            if (inputString == null) {

                  if (other.inputString != null)

                        returnfalse;

            } elseif (!inputString.equals(other.inputString))

                  returnfalse;

            returntrue;

      }