serialVersionUID in Java Serialization

Last modified on September 12th, 2014 by Joe.

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;

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: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2
	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)

Comments on "serialVersionUID in Java Serialization"

  1. Jigar says:

    Nicely simplified

  2. jayant says:

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

  3. jayant says:

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

  4. Ganesh says:

    A nice Read, Keep Posting.

  5. Praveen says:

    Simple and short as usual :)

  6. meen says:

    simplified explanation.
    Thank you

  7. Siva says:

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

  8. Santosh Subrahmanya says:

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

  9. Bora says:

    Great example. So thanks

  10. Irina says:

    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!

  11. Tito says:

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

  12. Ramesh says:

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

  13. vadhiraju says:

    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.

  14. pavan says:

    a good paragraph

  15. Shiny says:

    Thank you Joe! you really rock.

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

  16. Amir says:

    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.

  17. surjeet says:

    than2s s5r f6r th5s va34ab3e *6st

  18. Mohan says:

    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.

  19. Anonymous says:

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

  20. Hassan says:

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

  21. abinash says:

    i am happy about this concept

  22. sivaguru Natarajan says:

    Excellent *********

  23. Prabhat says:

    Such a nice explanation…..Thank u joe

  24. siddu says:

    Nice Post Thanks….

  25. nigam says:

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

  26. Anonymous says:

    Thanqu this tutorial is really good.

  27. Abhijai says:

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

  28. prakash says:

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

    thanks.

  29. Anonymous says:

    Its very nice explanation !.. Keep posted.

    Thanks,
    Ganesh

  30. Tirupathireddy Naredla says:

    Nice Post Thanks….

    Thanks,
    Tirupathireddy N

  31. Anonymous says:

    Nice concept !!

  32. ramkrishna says:

    Very good concept..

    Ram

  33. Anonymous says:

    Nicely explained..

    Thanks
    Abhishek

  34. Anonymous says:

    m gudu konda

  35. mastee says:

    too good………

  36. Java Learner says:

    Gud Explanation, with example. Keep Posting

  37. KishoreMadina says:

    Very Useful

  38. Alex says:

    Facinating, excelents explanation sir, tx a mil.

  39. harsh says:

    Just to Say thanks,

  40. Ramani says:

    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.

  41. Rohit Kumar says:

    Cool man nice blog

  42. Raghu says:

    Thanks for the blog.
    Neat explanation.

    -Raghu

  43. venkatesh.R says:

    Very Nice Explanation

  44. Sandeep says:

    Very precise document on Serialization ,

    Pics depicting real sense !

  45. Sai Pradeep Dandem says:

    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.?

  46. Maroof Ahmad says:

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

  47. Farid says:

    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

  48. Farid says:

    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

  49. Ganesh Shinde says:

    Its really good one.

  50. mraza says:

    Nice

  51. Chintan says:

    Nice Blog. Thanks

  52. shaik says:

    Very clear and easily undestable

  53. Tarun says:

    Hi Joe,
    Thanks for this very nicely composed article.

  54. Raj Mohamad says:

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

  55. Boopathi says:

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

  56. Boopathi says:

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

  57. Giri says:

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

  58. swarnalata patro says:

    can we serialize the resultset?

  59. Md Masoom says:

    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.

  60. Md Masoom says:

    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?

  61. Anonymous says:

    Good One Thank you Sir.

  62. dheerendra says:

    Most of doubts has been solved.
    thanks joe

  63. Rajkumar Chaudhary says:

    Fantastic code and Example is there

    thanks Joe

  64. Sai says:

    How can we serialize a static variable, its mentioned in many java books that a variable declared as static and transient cannot be serialized

  65. karunakar says:

    good example for Serialization

    Thanks

  66. sunil says:

    good example

  67. chandan kumar says:

    really grea8 work….joe keep it up…….man………………

  68. venu says:

    very nice and clear explanation…

    i have one query..what will happen if my proj having 2 classes has the same serial version uid.. will it be a problem????

  69. Raks says:

    Good one……

  70. Anonymous says:

    Solid Explanation

  71. Anonymous says:

    Explained very well..nice one

  72. Pragya says:

    Its too good…and clearly explained..

    Thanks

  73. Pooja says:

    Very nice, clean an effective explanation.
    Thanks for writing, keep it up :-)

  74. Arunkumar says:

    Your explaination is simply superup,
    Please can you explain why the serialVersionUID is in static and how this static field is beeing serialized.

  75. Rameswar says:

    thanks dude.. Nice explanation…

  76. Anonymous says:

    Great explanation.

    Thanks very much.

  77. manojbhi says:

    Nicely explained .. but What if i give same serialVersionUID to two classes

  78. chandrasekar says:

    Good Artical. Thanks for giving valuable informations

  79. Madhumathi says:

    Thanks for valuable information..keep posting

  80. vasu says:

    Nice Explanation

  81. dhRuv says:

    gr8 Job Sir

  82. Anonymous says:

    excellent explanation !!
    Keep going like this !

  83. Anonymous says:

    very very good……

  84. payal says:

    very very good…

  85. Rakesh says:

    Nice!! Very well explained :)

  86. Kapil says:

    “Even though serialVersionUID is a static field, it gets serialized along with the object” I just want to know what is the concept behind it. how serialVersionUID is serialized. And why they are doing like this otherwise they could have made serialVersionUID as simple instance varible then they can serialize the serialVersionUID. so my question is why and what is need?

  87. pkiran says:

    Nice blog

  88. Arsh says:

    If my class properities are being changed after serialization and then further if I deserialize it, then what happens..can you please through some light on this? thanks in advance

  89. Anonymous says:

    nice explanation..

  90. venkat says:

    good example

  91. venkat says:

    good example

  92. Roshan says:

    nice explanation

  93. RaghuGowda says:

    Nice Blog.. Keep Up doing the great work.

  94. agreed. how do you populate the FullClassName field on the show serialver panel

  95. Prabhat Verma says:

    very easy to understand…thanks

  96. selvamani says:

    The image at the beginning of the tutor looks cool and funny :P. Nice Article.

  97. venkat says:

    nice,u r explaining very good and simple ,easily understand everybody

  98. Anonymous says:

    Thanks

  99. Amit Kumar says:

    While I ran the test according to article I posted, I had left out “final” modifier of serialVersionUID, but the test ran without any problem. But When I rechecked the code I found the mistake and rectified. Thanks for sharing such an article. Also I would like to know the USE CASE of serialization that when it is used. I am java Enterprose web developer so let me know the context where it is used?

    Thanks
    Amit

  100. Anonymous says:

    Its an exelent explanation. I never seen this type of explanation so that it will help me to improve my knowledge.

    Thanks,
    David.

  101. Mukesh Kumar says:

    Sir, Great work…
    Thanks for the explanation….

  102. Saumitra Saxena says:

    Your contents in every tutorial are very authentic and nicely explained….

  103. Anonymous says:

    Vary nice article

  104. yuyuchen09 says:

    That is my question too.

    It is comparing, one value from the de-serialized object with the one declared in the class itself. If the serialVersionUID is absent, it’s calculated by a complex algorithm. Since different JVM implementations might have variations on the computation, that could result in a mismatch. That is why a serialVersionUID is highly recommended.

    The serialVersionUID only needed to be updated when there is incompatible type changes in the class. See more details in the spec,

    http://docs.oracle.com/javase/6/docs/platform/serialization/spec/version.html#6678

  105. yuyuchen09 says:

    This is not a problem, the version only matters in the context of the same Serializable class. You can consider it a version ID of the class.

  106. yuyuchen09 says:

    Since the version ID is used only within the context of the object versioning, I don’t see why this need to be computed using the serialver util, a simple “1L’, then “2L” would just do the same job.

  107. Ajitha says:

    what will happen after serialization any changes has been made?which exception we will get?

  108. Naveen says:

    Great work joe, till now I don’t know why we use serial vesrion id….

    Great post
    Keep posting

  109. sunny says:

    What happens when we serialze a singleton class (that is we implemented the serialize interface)?

    Then how singularity is maintianed.

  110. srikant singh says:

    Hi joe , if serial id is static then how it get serialized this question was asked by a company
    any one have an idea please reply

  111. Ashish Singhi says:

    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”.

  112. srikant singh says:

    So it is internally configuration in jvm for specially this field

  113. Jyoti says:

    gud 1

  114. Anonymous says:

    nicely explained…

  115. Rohit gupta says:

    Awesome ….
    pls explain how hashmap work internally….

  116. Anonymous says:

    superb explanation! After googling lot of stuffs, this one helps a lot. Thanks!

  117. Sanchit Gupta says:

    Simplest post with valuable and quick understandable knowledge.

  118. Akber Jaleel says:

    superb explanation!

  119. Saroj Kumar says:

    please provide pagination for list of comments on your website.
    It will add to the convenience for the page navigation.

    Thanks

  120. Ritika says:

    The language and example used by you is very helpful to understand the concept.

  121. jeevith says:

    Thanks a ton Joe,your blogs are really helping us …………..

  122. Rohan says:

    Hi,

    Can you please tell why some of the classes don’t have serialVersionUID like java.util.Arrays.

  123. Himanshu says:

    Explained in detail with simplest possible manner….

  124. Manjunath says:

    very Good example,simply super Sir

  125. vignesh says:

    ” My general note is, always pay attention to the java warning messages. It will help you to learn a lot of fundamentals.”
    — Thanks for this :)

  126. Ahmed says:

    Similar to the 2010 article from mkyoung.com but anyway Thanks.

  127. Mahesh says:

    Good explanation.

    Thanks
    Mahesh

  128. Mufim says:

    Please explain public vs private vs protected serialversionUID.Since we have to make unique serialversionUID why it is not private by default

  129. Ankush says:

    I still don’t understand why did you say – “As and when you change anything in the class, you should upgrade the serailVersionUID”??

    if I remove one of the property from my class(if I change serailVersionUID I wont be able to deserialize my old serialzed object but I don’t want that).

    I also dont understand why serailVersionUID should be unique?? if I have 10 classes under my project, I can give same UID to all the classes as the are not related to each other

  130. Aman Kumar says:

    Good example and explanation.Thank you Joe…

  131. udaykiranreddy desam says:

    Hummmmmmm ….. Good for start up but Please explain what happens if serialversion UID is same and fields are changed and what is case of 1L …. that will make this post better

  132. Bindu says:

    Simple and easy to understand.

    Excellant work done by you.

  133. venkat says:

    nice article joe

Comments are closed for "serialVersionUID in Java Serialization".