Java Serialization

Last modified on June 19th, 2017 by Joe.

Have you ever seen what is inside a serialized object? I will explain to you what is java serialization, then provide you with a sample for serialization. Finally, most importantly, let us 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.Store

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

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

Comments on "Java Serialization"

  1. ken says:

    Thanks for the insight on serialization

  2. Prafulla says:

    Serialization Concept explained nicely. Thanks for Details.

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

  4. Suresh says:

    Thanks so much for the good explanation on serialization

  5. Shadab says:

    Thanks for such a precise and clear understanding.

  6. Arpit says:

    Very neatly explained…!

  7. […] Also know some fundamentals of serialization. […]

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

  9. Nitin says:

    Hi there,

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

    Cheers
    Nitin.V

  10. Neha J says:

    You made serialization concept just so simple and understandable.

    Thanks and keep such articles coming up!

  11. Srilatha,K says:

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

  12. Jill says:

    Good Insight

  13. Sridhar says:

    Very Good Explanation. Its very understandable.Thanks

  14. Brijesh says:

    Nice understanding explanation..

    Thanks a lot

  15. Suwarna says:

    Hi

    Thanks the detail explanation.

    Regards,
    Suwarna

  16. Anand Garlapati says:

    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.

  17. divya says:

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

  18. Javin Paul says:

    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

  19. vidhi says:

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

    Please keep posting such a nice blogs.

    -Vidhi

  20. Akshata says:

    Explained in a very Simple Manner.
    Thank You.

  21. Madhukar Gunda says:

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

  22. swathi says:

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

  23. Jitendra Gupta says:

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

  24. Gourav says:

    Can you explain the Serialization using Externalizable interface?

    thanks in advance.

  25. Jagadish.K says:

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

  26. Sakthi Manoj says:

    Thank u for ur answer….!:-)

  27. Ashok Kumar says:

    Very Knowledge full about Serialization

  28. sonal says:

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

  29. sonal says:

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

  30. Nagraj says:

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

  31. wudeng says:

    very helpful, thanks.

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

  33. jnana says:

    i could not understand
    “serialization”

  34. sathish says:

    something good in this………

  35. Basavaraj says:

    Excellent creativity.

  36. santhosh says:

    Hi this is good

  37. sumit says:

    thanks to this site develpers

  38. John says:

    Can you give some explanation about SerialVersionUID in serialization

  39. sunil kumar chaurasia says:

    I appreciated it.It is very nice explanation.

  40. sunil kumar chaurasia says:

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

  41. Ramkrishna says:

    it is a good material for serialization….

    easily understandable

  42. […] 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 […]

  43. Dinesh says:

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

  44. abhijit says:

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

  45. mazhar says:

    please tell how to serialize object in xml

  46. mazhar says:

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

  47. Harish says:

    Excellent Material.

  48. […] 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 […]

  49. rahul says:

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

  50. SuresHK says:

    awesome Tutorial for Serialization

  51. Joe says:

    @rahul have a look at java string

  52. Anonymous says:

    Very neat and clear explanation which never read.

  53. Sunil Kumar says:

    its very nice def….

  54. Sunil Kumar Maghar says:

    Hi,
    This is very helpful example….

    Thanks
    Sunil Kumar

  55. prakash says:

    Good

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

  57. Anonymous says:

    Excellent work Joe!!
    – Shyam :)

  58. Anonymous says:

    Thanks..Very Helpfull document..

  59. Anonymous says:

    Thank you, it was good and very helpfull…

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

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

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

  63. emmanuel says:

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

  64. Shazz says:

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

  65. shiva panchal says:

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

    Thanks!!!!!

  66. Sakthi says:

    Nice representation of serialized object will look like. Thanks.

  67. Chintan says:

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

    Thanks
    Chintan

  68. santhosh d.k says:

    Good Explaination.

  69. sunil says:

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

  70. 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)

  71. Egyptian Man says:

    Great
    Thanks

  72. deepak says:

    thanks

  73. Anonymous says:

    thanku so much

  74. Anonymous says:

    great…………..

  75. Anonymous says:

    .

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

    ‘)

  77. Anonymous says:

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

  78. Anonymous says:

    good explaination

  79. Anonymous says:

    Just Superb

  80. Azhagumuthu G says:

    Simple, understandable and clear.
    Thanks

  81. 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);
    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?

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

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

  84. monika says:

    very well explained

  85. Divya says:

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

  86. twinkle says:

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

  87. Anonymous says:

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

    -Pramit(9723916656)

  88. Anonymous says:

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

    -Rajasekhar

  89. raju says:

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

  90. sivakumar says:

    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.

  91. sivakumar says:

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

  92. Jeevan says:

    Hi,

    Thanks & nice to see good work,

    Its very much useful

    Regards,
    Jeevan

  93. Amit says:

    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?

  94. Pankaj Sinha says:

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

  95. abdul basith says:

    very very nice example

  96. Srikanth says:

    Wow.. What a presentation JOE.

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

  97. Arti says:

    Amazing explanation.. Thanks

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

  99. rupesh says:

    compact and very good artical.

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

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

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

  103. kumar says:

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

  104. Anonymous says:

    Good work joe, we heartily appreciate this. :)

  105. jagan says:

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

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

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

  108. Jai Andhra says:

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

  109. vinoth says:

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

  110. Anonymous says:

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

  111. Anonymous says:

    nice…very usefull

  112. Anonymous says:

    nice…very usefull

  113. Kalyan Roy says:

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

  114. Siva says:

    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

  115. vivek says:

    Thanx for such a nice article.. good luck

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

  117. Sai says:

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

  118. Anonymous says:

    very nice….thanx..!!

  119. Anonymous says:

    good explanation fro serialization .Very nice thanx.

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

  121. uday says:

    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.

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

  123. Vinaya says:

    I had never understood Serilaization this better

  124. Sunitha says:

    Nice explanation. Simple & easy to understand.

  125. venkat says:

    very nice explation serialization

  126. Shash says:

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

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

  128. Joe says:

    A classic use case would be in integration projects.

  129. 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());
    System.out.println(serialB.getSerializableProp());

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

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

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

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

Comments are closed for "Java Serialization".