serialVersionUID in Java Serialization

08/01/2012

serialVersionUID is used to ensure that during deserialization the same class (that 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?

Lets start with annoying warning message you get in your IDE when you declare a class as Serializable.

The serializable 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. Refer this link for the algorithm to generate serialVersionUID.

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.

import java.io.Serializable;

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:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerialVersionUIDTest {

  public static void main(String args[]) throws IOException, ClassNotFoundException {
    Lion leo = new Lion("roar");
    // serialize

    System.out.println("Serialization done.");
    FileOutputStream fos = new FileOutputStream("serial.out");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(leo);

    // deserialize
    FileInputStream fis = new FileInputStream("serial.out");
    ObjectInputStream ois = new ObjectInputStream(fis);
    Lion deserializedObj = (Lion) ois.readObject();
    System.out.println("DeSerialization done. Lion: " + deserializedObj.getSound());
  }
}

Output:

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.

  1. Serialized Lion with serialVersionUID with 1L.
  2. Changed serialVersionUID to 2L and compiled and loaded the class.
  3. Deserialize the already serialized object and load it with the latest class.
  4. We get exception as serialVersionUID is not matching.
Exception in thread "main" java.io.InvalidClassException: Lion; local class incompatible: <strong>stream classdesc serialVersionUID = 1, local class serialVersionUID = 2</strong>
	at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
	at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
	at java.io.ObjectInputStream.readClassDesc(Unknown Source)
	at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
	at java.io.ObjectInputStream.readObject0(Unknown Source)
	at java.io.ObjectInputStream.readObject(Unknown Source)
	at SerialVersionUIDTest.main(SerialVersionUIDTest.java:21)

A nice Read, Keep Posting.

Ganesh on January 9th, 2012 6:38 am

Nicely simplified

Jigar on January 9th, 2012 6:39 am

Nice One.
can you share a some other aspects serialization.
it would be very helpful

jayant on January 9th, 2012 7:17 am

Nice One.
can you share a some other aspects of serialization.
it would be very helpful

jayant on January 9th, 2012 7:17 am

simplified explanation.
Thank you

meen on January 9th, 2012 9:27 am

Awesome explanation. And the best part is the picture :-)

Siva on January 9th, 2012 10:41 am

Wow !!! I used to ignore such a message everytime that I encountered one. Now I know the meaning of it. Nice post.

Santosh Subrahmanya on January 9th, 2012 11:58 am

Simple and short as usual :)

Praveen on January 9th, 2012 1:41 pm

Love your explanations of concepts. Whenever I need a visual note in my head of a concept, I always turn to your posts. I think it is genius to be able to say in such simple terms such convoluted topics. Keep posting!

Irina on January 9th, 2012 2:39 pm

The last example clearly explains the need for serialization , I think we shud pay attention to serialization when we use webservices right ?

Tito on January 9th, 2012 5:31 pm

very good stuff about serialVersion ID.
Thank you very much!

Ramesh on January 9th, 2012 7:22 pm

Great example. So thanks

Bora on January 9th, 2012 7:29 pm

i am very much satisfied with ur explanation. i am eager to learn lot of things in java. thanks a lot..

In the above explanation, the serialver tool is used where we installed java.
but our java class file is in some other folder like D:\sample\Test.java and java installed path is in c:\Program files\java\jdk1.6.0\bin. how to get serialuid for my Test.java class.

vadhiraju on January 10th, 2012 2:01 am

a good paragraph

pavan on January 10th, 2012 8:42 am

Thank you Joe! you really rock.

Best thing is the simplicity of your writing. Luv javapapers.

Shiny on January 10th, 2012 1:47 pm

Nice work Joe, Thanks for your article. I have a question. What will happen if we serialize an object in 1.5 JVM and deserialize in 1.3 with serialVersionUID?
Thanks in advance.

Amir on January 10th, 2012 7:07 pm

than2s s5r f6r th5s va34ab3e *6st

surjeet on January 11th, 2012 6:27 am

wow what a website…

thank youuu

Priya on January 11th, 2012 10:58 am

Its really nice one.
I think most of the developer don’t the fact why this warning is coming.keep posting.
Kindly Explain how serialization happening.How Compile know the object is implementing Serilization.

Mohan on January 12th, 2012 6:10 pm

I am glad to read this paper, it’s so helpful

Anonymous on January 13th, 2012 10:58 am

very good explanation.its really helpful for those who have interest in programming.

Hassan on January 13th, 2012 11:53 am

i am happy about this concept

abinash on January 16th, 2012 12:29 pm

Excellent *********

sivaguru Natarajan on January 17th, 2012 12:30 am

Such a nice explanation…..Thank u joe

Prabhat on January 19th, 2012 6:07 am

Nice Post Thanks….

siddu on January 20th, 2012 5:05 pm

Nice One.
can you share a some other aspects of serialization.
it would be very helpful

nigam on January 22nd, 2012 1:55 pm

Thanqu this tutorial is really good.

Anonymous on January 23rd, 2012 1:00 pm

Nicely explained..
WIll object serialized in one java version (Say 1.4) can deserilazed in another (Say 1.5 or 1.6)??

Abhijai on January 23rd, 2012 3:52 pm

well explained, now finally i understand the meaning of serialversionuid in java

thanks.

prakash on January 27th, 2012 1:50 pm

Its very nice explanation !.. Keep posted.

Thanks,
Ganesh

Anonymous on January 27th, 2012 3:15 pm

Nice Post Thanks….

Thanks,
Tirupathireddy N

Tirupathireddy Naredla on January 30th, 2012 4:46 pm

Nice concept !!

Anonymous on January 30th, 2012 7:54 pm

Very good concept..

Ram

ramkrishna on January 31st, 2012 3:45 pm

Nicely explained..

Thanks
Abhishek

Anonymous on February 1st, 2012 9:07 pm

m gudu konda

Anonymous on February 2nd, 2012 3:03 pm

too good………

mastee on February 7th, 2012 12:26 am

Really good post this one is…

Anupam Jain on February 7th, 2012 10:38 am

Gud Explanation, with example. Keep Posting

Java Learner on February 8th, 2012 2:39 pm

Very Useful

KishoreMadina on February 9th, 2012 5:18 pm

Facinating, excelents explanation sir, tx a mil.

Alex on February 12th, 2012 5:37 pm

Just to Say thanks,

harsh on February 17th, 2012 6:11 pm

Thanks for the nice article. Question: I understand that the serialVersionUID is read from the deserialized class, but I didnt get to which classes serialVersionUID it will be compared to.

Ramani on February 23rd, 2012 5:09 pm

Cool man nice blog

Rohit Kumar on March 6th, 2012 7:11 pm

Thanks for the blog.
Neat explanation.

-Raghu

Raghu on March 8th, 2012 4:57 pm

Very Nice Explanation

venkatesh.R on March 8th, 2012 6:20 pm

Very precise document on Serialization ,

Pics depicting real sense !

Sandeep on March 13th, 2012 12:25 pm

Nice explanation. :)
Your blog rocks !! I think i am too late to view your blog. Simple and clear explanations. Appearance of blog creates more interest while reading. :)

Apart from this, is it possible to make the page width a little wider.?

Sai Pradeep Dandem on March 17th, 2012 12:08 am

Really impressed,
Your writing style is to much clear and easily can understand . Thanks

Maroof Ahmad on March 17th, 2012 7:21 pm

if we use serializaion to sava an object on memory then we modify that class(definatly object has changed now) now we deserialize that object what will be happen, kindly answer

Farid on March 20th, 2012 2:46 pm

if we use serialization to save an object on memory then we modify that class(definatly object has changed now) now we deserialize that object what will be happen, kindly answer

Farid on March 20th, 2012 2:47 pm

Its really good one.

Ganesh Shinde on April 4th, 2012 10:25 am

Nice

mraza on April 4th, 2012 6:29 pm

Nice Blog. Thanks

Chintan on April 11th, 2012 6:59 pm

Very clear and easily undestable

shaik on April 13th, 2012 11:49 pm

Hi Joe,
Thanks for this very nicely composed article.

Tarun on April 20th, 2012 8:36 pm

it is really good…joe..and it is helpful for me.

Raj Mohamad on May 3rd, 2012 9:07 am

nice know about the serialVErsionUID. super keep post more. good.

Boopathi on May 10th, 2012 9:46 am

nice know about the serialVErsionUID. super keep post more. good.

Boopathi on May 10th, 2012 9:46 am

I don’t agree with ”This is one exception to the general serialization rule that, “static fields are not serialized”.

Giri on May 10th, 2012 5:22 pm

can we serialize the resultset?

swarnalata patro on May 17th, 2012 12:26 pm

I am confused with ”This is one exception to the general serialization rule that, “static fields are not serialized”.”
If Static field not serialized then what diff with transient.

Md Masoom on May 18th, 2012 12:33 pm

I am confused with ”This is one exception to the general serialization rule that, “static fields are not serialized”.”
If Static field not serialized then what diff with transient?

Md Masoom on May 18th, 2012 12:34 pm

Good One Thank you Sir.

Anonymous on May 18th, 2012 6:08 pm

Most of doubts has been solved.
thanks joe

dheerendra on May 23rd, 2012 12:48 pm

Fantastic code and Example is there

thanks Joe

Rajkumar Chaudhary on May 26th, 2012 10:51 pm


Email:

about
I am Joe, author of this blog. I run this with loads of passion. If you are into java, you may find lot of interesting things around ...more about me. Google+
java badge
Home