Java Serialization

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;


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");

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

	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 added on 23/11/2009.



Comments on "Java Serialization"

  1. Karthikeyan says:

    Good teaching sir. But I have a doubt. Can you explain why we need to implement serializable interface as we are not creating any bond? Can you please explain what we achieve by implementing serializable interface.

  2. Anonymous says:

    State is nothing but the values stored in member variables of a class. Class has two things state and behavior, State is nothing but member variables and Behavior are the member functions of a class. For example consider a Employee class where states/variables will be name, age, id etc., whereas doWork(), applyLeave() will be behavior of the class.

  3. Mini says:

    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();
    FileOutputStream fileOutputStream;
    try {
    File file = new File(“/tmp/test.out”);
    fileOutputStream = new FileOutputStream(“/tmp/test.out”);
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

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

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

    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.

    • Pavan says:

      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

  4. Anonymous says:

    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());

  5. Chennu says:

    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

  6. Shash says:

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

  7. venkat says:

    very nice explation serialization

  8. Sunitha says:

    Nice explanation. Simple & easy to understand.

  9. Vinaya says:

    I had never understood Serilaization this better

  10. Rohit says:

    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……

  11. uday says:


    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.

  12. Swapnil Joshi says:

    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.

  13. Anonymous says:

    good explanation fro serialization .Very nice thanx.

  14. Anonymous says:

    very nice….thanx..!!

  15. Sai says:

    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 :)

  16. vivek says:

    Thanx for such a nice article.. good luck

  17. Siva says:


    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();


    Could tell me.


    • Sai says:

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

      transient String third_ele = “three”;

      Hope this works :)

  18. Kalyan Roy says:

    Your explanations help me a lot…
    Thanks and keep writing…

  19. Anonymous says:

    nice…very usefull

  20. Anonymous says:

    nice…very usefull

  21. Anonymous says:

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

  22. vinoth says:

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

  23. Jai Andhra says:

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

  24. Anonymous says:

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

  25. Anonymous says:

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

  26. jagan says:

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

  27. Anonymous says:

    Good work joe, we heartily appreciate this. :)

  28. kumar says:

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

  29. Milind says:

    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

  30. kanuj bhatnagar says:

    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.

  31. Anonymous says:

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

  32. rupesh says:

    compact and very good artical.

  33. Abhijit R says:

    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 .

  34. Arti says:

    Amazing explanation.. Thanks

  35. Srikanth says:

    Wow.. What a presentation JOE.

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

  36. abdul basith says:

    very very nice example

  37. Pankaj Sinha says:

    Thanks a lot for providing such good technical stuff.

  38. Amit says:

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

  39. Jeevan says:


    Thanks & nice to see good work,

    Its very much useful


  40. sivakumar says:

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

  41. sivakumar says:

    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.

  42. raju says:

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

  43. Anonymous says:

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


  44. Anonymous says:

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


  45. twinkle says:

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

  46. Divya says:

    Great!!!!!!! Explanations are clear and simple

  47. monika says:

    very well explained

  48. Sachin Raghav says:

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

  49. anupriya says:

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

  50. Anonymous says:

    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);

    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?

  51. Azhagumuthu G says:

    Simple, understandable and clear.

  52. Anonymous says:

    Just Superb

  53. Anonymous says:

    good explaination

  54. Anonymous says:

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

  55. Anonymous says:

    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.


  56. Anonymous says:


  57. Anonymous says:


  58. Anonymous says:

    thanku so much

  59. deepak says:


  60. Egyptian Man says:


  61. Eugene says:

    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)

  62. sunil says:

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

  63. santhosh d.k says:

    Good Explaination.

  64. Chintan says:

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


  65. Sakthi says:

    Nice representation of serialized object will look like. Thanks.

  66. shiva panchal says:

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


  67. Shazz says:

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

  68. emmanuel says:

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

  69. sapan says:

    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

  70. Anonymous says:

    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.

  71. ganesh says:

    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

  72. Anonymous says:

    Thank you, it was good and very helpfull…

  73. Anonymous says:

    Thanks..Very Helpfull document..

  74. Anonymous says:

    Excellent work Joe!!
    – Shyam :)

  75. Ganesh Machkure says:

    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();

  76. prakash says:


  77. Sunil Kumar Maghar says:

    This is very helpful example….

    Sunil Kumar

  78. Sunil Kumar says:

    its very nice def….

  79. Anonymous says:

    Very neat and clear explanation which never read.

  80. Joe says:

    @rahul have a look at java string

  81. SuresHK says:

    awesome Tutorial for Serialization

  82. rahul says:

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

  83. [...] is an interface that enables you to define custom rules and your own mechanism for serialization. Serializable defines standard protocol and provides out of the box serialization [...]

  84. Harish says:

    Excellent Material.

  85. mazhar says:

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

  86. mazhar says:

    please tell how to serialize object in xml

  87. abhijit says:

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

  88. Dinesh says:

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

  89. [...] have seen enough about using the default protocol to implement serialization and how instances are created during serialization. In this current article we shall see about [...]

  90. Ramkrishna says:

    it is a good material for serialization….

    easily understandable

  91. sunil kumar chaurasia says:

    sir I want to some easy example of file handling,java bean,and networking.I need must.
    thank u sir

  92. sunil kumar chaurasia says:

    I appreciated it.It is very nice explanation.

  93. John says:

    Can you give some explanation about SerialVersionUID in serialization

  94. sumit says:

    thanks to this site develpers

  95. santhosh says:

    Hi this is good

  96. Basavaraj says:

    Excellent creativity.

  97. sathish says:

    something good in this………

  98. jnana says:

    i could not understand

  99. muthu says:

    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

  100. wudeng says:

    very helpful, thanks.

  101. Nagraj says:

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

  102. sonal says:

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

  103. sonal says:

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

  104. Ashok Kumar says:

    Very Knowledge full about Serialization

  105. Sakthi Manoj says:

    Thank u for ur answer….!:-)

  106. Jagadish.K says:

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

  107. Gourav says:

    Can you explain the Serialization using Externalizable interface?

    thanks in advance.

  108. Jitendra Gupta says:

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

  109. swathi says:

    Can i serialise any type of data,means i want to serialise print it possible???????

  110. Madhukar Gunda says:

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

  111. Akshata says:

    Explained in a very Simple Manner.
    Thank You.

  112. vidhi says:

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

    Please keep posting such a nice blogs.


  113. Javin Paul says:


    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.


  114. divya says:

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

  115. Anand Garlapati says:

    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?


    Anand Garlapati.

  116. Suwarna says:


    Thanks the detail explanation.


  117. Brijesh says:

    Nice understanding explanation..

    Thanks a lot

  118. Sridhar says:

    Very Good Explanation. Its very understandable.Thanks

  119. Jill says:

    Good Insight

  120. Srilatha,K says:

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

  121. Neha J says:

    You made serialization concept just so simple and understandable.

    Thanks and keep such articles coming up!

  122. Nitin says:

    Hi there,

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


  123. Sandeep Kumar says:

    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!!!

  124. [...] Also know some fundamentals of serialization. [...]

  125. Arpit says:

    Very neatly explained…!

  126. Shadab says:

    Thanks for such a precise and clear understanding.

  127. Suresh says:

    Thanks so much for the good explanation on serialization

  128. Omar says:

    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?

  129. Prafulla says:

    Serialization Concept explained nicely. Thanks for Details.

  130. ken says:

    Thanks for the insight on serialization

Comments are closed.