Java Serialization

23/11/2009

Have you ever seen what is inside a serialized object? I will explain you what is java serialization, then provide you with a sample for serialization. Finally most importantly, lets explore what is inside a serialized object and what it means. That is internals of java serialization and how does it works. If you want to have your own implementation of java serialization, this article will provide you with a good platform to launch.

What is Java Serialization?

Primary purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again. When there are two different parties involved, you need a protocol to rebuild the exact same object again. Java serialization API just provides you that. Other ways you can leverage the feature of serialization is, you can use it to perform a deep copy.

Why I used ‘primary purpose’ in the above definition is, sometimes people use java serialization as a replacement for database. Just a placeholder where you can persist an object across sessions. This is not the primary purpose of java serialization. Sometimes, when I interview candidates for Java I hear them saying java serialization is used for storing (to preserve the state) an object and retrieving it. They use it synonymously with database. This is a wrong perception for serialization.

How do you serialize?

When you want to serialize an object, that respective class should implement the marker interface serializable. It just informs the compiler that this java class can be serialized. You can tag properties that should not be serialized as transient. You open a stream and write the object into it. Java API takes care of the serialization protocol and persists the java object in a file in conformance with the protocol. De-serialization is the process of getting the object back from the file to its original form.

Here protocol means, understanding between serializing person and de-serializing person. What will be the contents of file containing the serialized object? This serves as a guideline to de-serialize. Have a look at the following sample and how its serialized file looks.

Sample Source Code for Java Serialization

package com.javapapers.sample;

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

class SerializationBox implements Serializable {

	private byte serializableProp = 10;

	public byte getSerializableProp() {
		return serializableProp;
	}
}

public class SerializationSample {

	public static void main(String args[]) throws IOException,
			FileNotFoundException, ClassNotFoundException {

		SerializationBox serialB = new SerializationBox();
		serialize("serial.out", serialB);
		SerializationBox sb = (SerializationBox) deSerialize("serial.out");
		System.out.println(sb.getSerializableProp());
	}

	public static void serialize(String outFile, Object serializableObject)
			throws IOException {
		FileOutputStream fos = new FileOutputStream(outFile);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(serializableObject);
	}

	public static Object deSerialize(String serilizedObject)
			throws FileNotFoundException, IOException, ClassNotFoundException {
		FileInputStream fis = new FileInputStream(serilizedObject);
		ObjectInputStream ois = new ObjectInputStream(fis);
		return ois.readObject();
	}
}
Ads by Google

Exploring Java Serialization

Look at following image. After serializing ‘SerializationBox’ in the above sample code, I opened the output in a hex editor. You can use Notepad++ and hex plugin to open the serialized file.

Let us look at contents byte by byte and find out what they are. It starts with “ac ed”. It is is called STREAM_MAGIC. It is a magic number (java API guys says) that is written to the stream header. It denotes that is start of serialzed content.Serialized Output

Similarly every character has a meaning. Actually the serialized file is more bulkier than you would expect, as it has a huge header the meta information of the classes involved and finally the content. Object Serialization Stream Protocol have a look at chapter 6.4.2 Terminal Symbols and Constants. It gives you list of symbols and constants used in serialization.

Decrypting Serialized Java Object

In the image, I have underline a unit of information in a separate color for you to easily identify.

ac ed – STREAM_MAGIC – denotes start of serialzed content
00 05 – STREAM_VERSION – serialization version
73 – TC_OBJECT – new Object
72 – TC_CLASSDESC – new Class Descriptor
00 26 – length of the class name
63 6f 6d 2e 6a 61 76 61 70 61 70 65 72 73 2e 73 61 6d 70 6c 65 2e 53 65 72 69 61 6c 69 7a 61 74 69 6f 6e 42 6f 78 – class name
57 fc 83 ca 02 85 f0 18 – SerialVersionUID
02 – this object is serializable
00 01 – count of properties in the serialzed class – one property in our example
42 00 10 – private byte
73 65 72 69 61 6c 69 7a 61 62 6c 65 50 72 6f 70 78 70 – property name – serializableProp in our example
0a – 10 the value – This is the persisted value of the property in our sample

This Core Java tutorial was posted on 23/11/2009.
Ads by Google

296 comments on “Java Serialization

  1. Serialization Concept explained nicely. Thanks for Details.

  2. Simple and easy-to-understand explanation. I liked the use of a broad use tool like notepad++ and the Constant mapping. By the way, in wich class this constans are defined?

  3. Excellent technical stuff, i ever came across on Blogs. Looking forward for new subjects

  4. Thanks so much for the good explanation on serialization

  5. Thanks for such a precise and clear understanding.

  6. Pingback: Serialize / De-Serialize Java Object From Database

  7. Today only I visited this site for the first time and wow..I am in love with its content….very informative indeed. Well its now in my fav list and I have planned to read one topic per day.

    Thanks a lot for creating such a useful blog!!!

  8. Hi there,

    Nice Explanation in simple and precise format.
    keep writing :) .

    Cheers
    Nitin.V

  9. You made serialization concept just so simple and understandable.

    Thanks and keep such articles coming up!

  10. Nice and easily understandable explanation for java serialization. I have never came across this before.

  11. Very Good Explanation. Its very understandable.Thanks

  12. Nice understanding explanation..

    Thanks a lot

  13. Hi

    Thanks the detail explanation.

    Regards,
    Suwarna

  14. Hi,
    It is very good material on serialization. But i have one doubt.

    In EJB we have ejbActivate() and ejbPassivate() methods. In CMP beans the container will serialize the object in ejbActivate() and deserialize in ejbPassivate() methods. Here we are not tranporting the objects via streams to other PCs using serialization protocol. Please explain me in the context of EJB serialization and deserialization?

    Thanks

    Anand Garlapati.

  15. Thanks for giving me this type of information.
    This is a very nice and easy to understande.

  16. Hi,

    Just to add while writing Serializable class , its good practice to put a Seriazlizable alert in file so that when some one else add a new field in the class he must ensure that field is either transient or Serializable , so that Serializability of class should not break.

    Thanks
    Javin

  17. Thanks 4 clearing my serialization concept.

  18. Pingback: Singleton Pattern

  19. Explained very nicely and each line has clear message………….

  20. Nice to see detail description,it helps alot to understand internal details.

    Please keep posting such a nice blogs.

    -Vidhi

  21. Pingback: 单例模式 | Java视点

  22. Really good knowledge i got on java serialization

    Thanks
    Prasanna

  23. Explained in a very Simple Manner.
    Thank You.

  24. Its very nice artice , but please cover the Serialization UID concept indetail.

  25. good knowledge i got on java serialization, but please trasiant varible concept indetails.

  26. WOW…..SUPERB GOOD JOB DUDE…Continue with super stuff

  27. Can i serialise any type of data,means i want to serialise print preview.is it possible???????

  28. The explanation is very simple and clear. Thanks.

  29. very nice stuffs :)
    beautiful way of presenting :)
    Thank you very much :)
    Sandeep

  30. Its very nice artice , but please cover the Serialization whole concept in detail

  31. Nice Article. Explained in simple manner.

  32. Can you explain the Serialization using Externalizable interface?

    thanks in advance.

  33. Serialization Concept has been explained in a simple but easily understandable manner….
    Its really cool…

  34. nice one,it is very easy to understand…
    Thanks

  35. Very nicely explained.
    Good blog.

    Thanks
    Neha T

  36. very nice… at last found a good website 4 java learning

  37. can we implement Serialization on images…
    basically i want image to be converted in binary form..
    pls reply

  38. easy way to learn from this site……?

  39. very nice discription
    thamks alit!!!!!!!!!!!!!!!!!

  40. Thanks for providing such tough topic in an easiest way…..

  41. Very nice. Above contents are helpful to all.

    Thanks for such a great work.

    Could you please add more examples like serializing images or Resultset,It will be more helpful

  42. SIR AWESOME CODE AND EXCELLENT AND STUDENTS ARE EXACTLY IMPROOVING THERE KNOWLEDGE AUTOMATICALLY BY READ THIS CONCEPT

    THANKING YOU SIR ,

  43. Can you give some explanation about SerialVersionUID in serialization

  44. it is a good material for serialization….

    easily understandable

  45. Thanks a lot .I came to know a lot about SERIALIZATION .

  46. Pingback: Object Construction in Serialization

  47. awesome yaar………
    got to know something new and real helpful
    and easy to unerstand..

    thnx…

    keep it up…..

  48. Pingback: Customize Default Serialization Protocol

  49. Please tell me the difference between serialization, transcient and clonable?.

  50. This is awesome. I am very much clear about serialization

  51. Nicely Explained. Good work dude….
    Keep Posting different Topics On java.
    thx

  52. hey really nice blog… keep it up
    very good explanation
    thank u….

  53. please tell how to serialize object in xml

  54. thanks to make us understand.
    please tell how we use xml in serialization.
    and how we convert object to xml form.

  55. Pingback: Externalizable vs Serializable

  56. Hi Joe , can you explain why strings are immutable in java???

  57. Very neat and clear explanation which never read.

  58. Hi,
    This is very helpful example….

    Thanks
    Sunil Kumar

  59. Nice way of presentation.

    I have a question regarding de-serialization.
    First you serialize a object SerializationBox and write it to a file outfile.ser. On a different JVM i take the outfile.ser file and try to deserialize it using readObject() but i get java.lang.ClassNotFoundException as there is no class file sent.

    How does it reconstruct the object and type cast to the SerializationBox object?

    I know the file contains Class information as shown in the hex-format. but how do you write code to use readObject and typecast to the serialized object.

    SerializationBox reconstructedSBX = SerializationBox ois.readObject();

  60. Thank you, it was good and very helpfull…

  61. i have a small doubt:

    1)difference between creating a thread by extending Thread class and by implementing Runnable interface? Which one should prefer?

    please help me

  62. Hi Ganesh,

    I as know we should prefer implementing Runnable always as you don’t need to create multiple abject of your class to create multiple threads when required.

    There may be other uses/advantages of it.

  63. If we save the object state in a file in one system, then how we will get back the same state in another system to rebuild the object from the same state

    please answer this properly with detail

  64. if we declare a type as transient how it is not serialized ..pls explain..

  65. Hi,
    Thanks n appreciate your efforts…

  66. Hello,
    This is very nice & easy to understand.

    Thanks for your fantastic efforts.

    Regards,

  67. thanks sir…i m confused with serializable topic…now i understood a lot by ur explanation……

    Narayan Rao

  68. Hi Joe,

    Its nice blog. explanation is very good.

    thanks
    srini

  69. Thnx for easy representation…..

    From:pinky maher
    April 02;2012

  70. Wonderful.. thank you Sir please keep on writing.
    I am waiting for your more blogs.
    thanks a lot!!

  71. I was little confused before but as per your explaination it is now clear for me.

    Thanks!!!!!

  72. Nice representation of serialized object will look like. Thanks.

  73. Hi Joe,
    Awesome Tutorial on Serialization.
    I never see the easiest tutorial like yours.

    Thanks
    Chintan

  74. thanks for a deep explanation .it really necessary for all java developers.
    thanks a lot.

  75. Thanx for the good article. It helped me a lot. But there are some errors in bytecode:

    42 is `B` which means byte (not a private),
    00 10 73 65 72 69 61 6c 69 7a 61 62 6c 65 50 72 6f 70 – property name `serializableProp` in modified UTF-8
    78 – TC_ENDBLOCKDATA – classAnnotation (empty, no annotations)
    70 – TC_NULL – superClassDesc (superclass is Object)

  76. Content is too good but due to Background picture ,content is not visible effectively.
    please change Background pic or change font color and Keep writing..
    ThankYou.

  77. hey thanks for deep dive in serialization…

  78. this is very good Example and very helpful
    thanks to make me understood about java serialization…….

  79. awesome explanation keep adding more…..
    i dint find such a clear explanation in any other sites

    Regards,
    pavan

  80. Very Nice Article. Concept is explained in simple manner……….. Thanks a lot Bro

  81. Pingback: Java Annotations

  82. THANKS A LOT FOR DEEP EXPLANATION :-)

  83. Very Good to learn in a simple way…
    Thanks Joe…

  84. The beauty of your writting is that you write in a very simple and clear manner…

    always a pleasure reading you..

    Thankx a ton Joe

  85. The beauty of your writting is that you write in a very simple and clear manner…

    always a pleasure reading you..

    Thankx a ton Joe

  86. insert java values(’1′,’
    Java Interview Questions

    With the notable increase in jobs that involve extensive use of Java it certainly is worth devoting an entire section to this programming language. Of course, this is not a complete and thorough guide to Java, so some basic knowledge of Java is assumed. What’s being presented here are some salient questions that cover a broad range of topics in Java.

    Unless you are interviewing for a position that involves extensive use of Java, you generally won’t be asked Java-related questions. But if you know that the position requires at least some Java skills, you will definitely want to read this section.

    ‘)

  87. sorry joe i was trying to make how to create comment box ..so i have done this non sense

  88. Simple, understandable and clear.
    Thanks

  89. can you please add serialVersionUID importance?

  90. Hi Joe,
    I have some doubt…
    suppose I have a class that implements Serializable interface. Inside the class I don’t writes the code to persisting the object state like in your code

    public static void serialize(String outFile, Object serializableObject)
    throws IOException {
    FileOutputStream fos = new FileOutputStream(outFile);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(serializableObject);
    }

    public static Object deSerialize(String serilizedObject)
    throws FileNotFoundException, IOException, ClassNotFoundException {
    FileInputStream fis = new FileInputStream(serilizedObject);
    ObjectInputStream ois = new ObjectInputStream(fis);
    return ois.readObject();
    }

    So, my questions is, with the above scenario, is this a valid implementation of serialization? if Yes, then how JVM persist the state of object?

  91. Thank u.explained in simple words,easy to understand

  92. nice blog…very helpful….thnx..

    will u plz enlighten us on 1 more point..
    y serializable interface is used though it dont hav ny methods?????

  93. Thanks for giving the detail of Serialization.i have better understand the serialization through your tutorial.but what is marker interface?Explain briefly.
    Please reply me………….

  94. Thanks for your neat and clean explanation !

  95. Thanks for the brief explanation.Can u help me siving some information on Struts 2?

    Thanks ,

    Ayan Ray

  96. this is really useful .way of presentation is so nice.

    Thanks,
    Pavan

  97. This is really useful for me..
    and the explanation is excellent .
    Thanks
    Sumalatha

  98. Hi,

    Thanks for good explanation.Has explained in depth.

  99. can you explain where serialization can useful in web application?

  100. first time reading dis block nice expalnation.i have a doubt a class dat implements a serailized and class members are serialized. in the above example ssn is not serialized then how ssn variable sent into stream. plz send the answer to my mail abdularif09@gmail.com

  101. Very neat and Clearn explanations.
    Good Job.
    Adding other benefits of serialization would be better.

  102. Great!!!!!!! Explanations are clear and simple

  103. are all the functions of java implicitly virtual????

  104. wow…now,its very easy for me to explain in my exam.. thanxx Joe……

    -Pramit(9723916656)

  105. very nice explanation so far i have surfed over. Thanks a lot.

    -Rajasekhar

  106. sir i have one doubt
    which action java platform restrict on applet?

  107. hi
    without implements Serializable i can able to write and read the object in standalone as well as in network using ObjectOutputStream and ObjectInputStream. Please explain, is it must to implements Serializable interface. waiting for your reply.

  108. hi,
    Sorry to ask previous question.i Serializable the arrayList and vector objects.so i confused, now only saw that the both original class implements Serializable..

  109. Thanks for such a clear understanding of serialization….I am really impressed by the contents of ur website.hats off man…

  110. Hi,

    Thanks & nice to see good work,

    Its very much useful

    Regards,
    Jeevan

  111. Hi…
    I hav a doubt..can we serialize a object without any property ie A class without any property?
    Ex–
    class A implements Serializable{
    }
    Class Test{
    public static void main(String ag[]){
    —-code for serialzation of class A–
    }}
    Can it will serialize?

  112. Hi,
    Thanks a lot for providing such good technical stuff.

  113. Wow.. What a presentation JOE.

    Real good work. Hope to see other topics as well..!!

  114. Hi Joe,

    Nice articles, reading continously from 2 hours,

    Your style of writing article makes it interesting.

    I think ,I am in a new world of java.

    Keep it up .

  115. 1 Question:
    If we serialize a object in one JDK version and try to deserialize it in different JDK version; it is get deserialized?

  116. its too good and brief explanation
    thanks

  117. its complete and brief explanation
    THANKS

  118. very useful and i’m understand the concepts very clearly…. nice e.g

  119. Today only I have entered this site for the first time and fantastic..
    Thanks a lot for creating such a useful blog!!! please Keep update future….

  120. You should also mention that upon deserialization if the compiler finds the class missing/unreachable for the serialized object, it’ll throw an Exception. It becomes the responsibility of the deserializing code to include the appropriately required classes.

  121. Wow sir really dis is very helpful 4 me thanksssss a lot sir…..

  122. It’s very easy to understand and clears detail concepts about serialization.
    Thanx!

  123. its really good, but what is the exact use of serialization

  124. All of your posts are very good. They are easy to understand & very clearly explained from a novice point of view. Please keep posting such topics related to Java.

  125. suppose there are 2 User A and B, if A impliments serialization in one java class(means writting instance variable on socket and passing it to another side) and pass it over the network and User B sends one java class instance variable using socket to another side without serializing its class
    now at recevier side User C is receving data so what ADVANTAGE will get to User C when it recevies data from User A

  126. Thanks for such a nice explanation about serialization..

  127. there is no methods and no fields in serializable interface.how can store a state of an object.
    please explain i am confuse.

  128. Good work joe, we heartily appreciate this. :)

  129. Nice tutorial., keep doing the good work..,

  130. Very nice tutorial..
    I used to go through your blog before my interview,. Thank you so much for explaining clearly,.. Great Work,.. Keep going

  131. very good to have a site like this to understand the java concepts in very simple and clear way . thanks to blog owner

  132. Aree joe anna…mast cheppivanee conceptuu…ne article kiraak unnai anna…gitlanee ee blog continue cheyi…

  133. wow..what an explanation about serilalization..u made it easy..

  134. can u plz tell me the exact difference between wildcard and bounded variable in collections….

  135. Hi,

    The above description and code snippet of Serialization was really helpful to me.

    I had a quick question on this. When we serialize an object, is it creating a new instance of the object or creating a copy of it?

    • Deserialization is like constructor, so here you create a new object.

  136. Hi,

    very nice.
    I am fighting years to learn serialization. Now I understood.

    I have a question. Serlization makes Object heavy, Why all hibernate entities are considered as Serializable.

  137. Nice Tutorial. Now got what serialization means.

  138. Hey thats really very very nice explaination , plz tell me that in this example why did not we implement marker interface ?

  139. Nice way of representation. Thanks !!!!!!! said on ,

    Nice way of representation. Thanks !!!!!!!

  140. excellent article – liked the usage of hex plugin of Notepad++

  141. hi, when will we use the serialization and the object output stream.. what will be the difference when i use the object output stream instead of the serialization.

  142. This concept is good..
    But how to serializa and deserialize an image is it the same way as the above..

  143. Hey,

    I have understood the Serialization and deSerialization how does internally works in java.

    Thanks for explaining the core stuff.

    I have one doubt that is eating my head.

    I am holding an ArrayList . I would not like to serialize the 3 rd element from an my ArrayList. How to do that?

    List li = new ArrayList();

    li.add(“one”);
    li.add(“two”);
    li.add(“three”);

    Could tell me.

    Thanks,
    -Siva

    • Hi Shiva,
      You can declare some String literal for third element and declare it as transient.

      Ex:
      transient String third_ele = “three”;

      Hope this works :)

  144. Thanx for such a nice article.. good luck

  145. Very good article Joe. I know what exactly serialization is. But, as a programmer, I was always interested to see the serialization file and it’s format and header and stuff. This blog is really good and informative. Keep up the good work :)

  146. good explanation fro serialization .Very nice thanx.

  147. Pingback: Java Binary

  148. Pingback: Java Double Brace Initialization

  149. It would be nice to have a subtopic on readObject() and writeObject() methods from ObjectInputStream and ObjectOutputStream. Without that the topic can not be complete.

  150. Sir,

    Your concepts are really super.
    I have one doubt about serialization.
    Why we need to serialize object?
    When we use in real time?
    Please answer.

  151. Can you please Explain how can we append an objects to a file which already contains some objects… and i want to read all objects
    it gives an StreamCorrupted Exception ..when i try to read an objects i recently appended……

  152. the hex file description at the end was awesome

  153. I had never understood Serilaization this better

  154. Nice explanation. Simple & easy to understand.

  155. Never came across such detailed explanation of Serialization. Thanks for sharing. Awesome blog.

  156. Only one world for this blog is Excellent..!!!!!!!!!!!!!!!!
    :)
    Keep Writing ….

  157. I have a strange question for you. What is the need for sending the object over the network. Why we need to send. Can you please explain with an example or rough design

  158. Super joe, Nice and very very good article

  159. Thank you Mr.Joe your explanation was really good!

  160. it is really very useful……Thank You

  161. whoa! mind = blown!

    thanks for this example friend :)

  162. When i compile the code which you have given am getting the output as 10. I thought the object was deserialized. But if i comment the method deserialize and execute the above method , it is returning as 10. please clarify Joe for my below code,i would like to serilaze the object
    SerializationBox serialB = new SerializationBox();
    serialize(“serial.out”, serialB);
    // SerializationBox sb = (SerializationBox) deSerialize(“serial.out”);
    // System.out.println(sb.getSerializableProp());
    System.out.println(serialB.getSerializableProp());

  163. It is said that static fields cannot be serialized.
    public class SerializableExample implements Serializable{

    private static Integer staticInteger = new Integer(0);

    public static void main(String[] args) {
    SerializableExample example = new SerializableExample();
    example.setStaticInteger(20);
    FileOutputStream fileOutputStream;
    try {
    File file = new File(“/tmp/test.out”);
    fileOutputStream = new FileOutputStream(“/tmp/test.out”);
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
    objectOutputStream.writeObject(example);

    FileInputStream fileInputStream = new FileInputStream(“/tmp/test.out”);

    ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
    SerializableExample serializableExample1 = (SerializableExample) objectInputStream.readObject();
    System.out.println(serializableExample1.getStaticInteger());
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    public static Integer getStaticInteger() {
    return staticInteger;
    }

    public static void setStaticInteger(Integer staticInteger) {
    SerializableExample.staticInteger = staticInteger;
    }
    }

    The above program should have returned 0 . But it returns 20.

    • you are performing both serialization and deserialization on same class.As Static variables are class variable the value is still 20.try deserialization in other class

  164. Thanks for the simple tutorial – Java serialization.
    i was searched many sites, but finally i understood what is Java serialization.

  165. Hi Sir,
    Thanks for explaining Java Serialization in such a nice descriptive way. I really admire the way you present the topics in this blog. Thanks again. Awaiting more concepts and tutorials :)

  166. if any sub class implements serializable but super class is not implements then the object will be serialized?

    • if any sub class implements serializable but super class is not implements then the object will be serialized?
      And when it gives error if super class not implements serializable

  167. Hi Joe,

    In my understanding, an object is an entity which hold the reference of memory.If so, how the object from one JVM to another JVM works?

    Please clarify me on this.

    Regards,
    Sivakumar.

  168. you have explained Serialization in depth and it is understandable. Thanks for the information

  169. Pingback: Java Clone, Shallow Copy and Deep Copy

  170. you explained what and how? can you also explain why we need Serialization? i came across in the internet about to maintain state of the object. what is exactly state?

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>